Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correctly convert a Float to a JsNumber using BigDecimal#decimal #241

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/main/scala/spray/json/JsValue.scala
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ object JsNumber {
val zero: JsNumber = apply(0)
def apply(n: Int) = new JsNumber(BigDecimal(n))
def apply(n: Long) = new JsNumber(BigDecimal(n))
def apply(n: Float) = n match {
case n if n.isNaN => JsNull
case n if n.isInfinity => JsNull
case _ => new JsNumber(BigDecimal(java.lang.Float.toString(n)))
}
def apply(n: Double) = n match {
case n if n.isNaN => JsNull
case n if n.isInfinity => JsNull
Expand Down
7 changes: 4 additions & 3 deletions src/test/scala/spray/json/BasicFormatsSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ class BasicFormatsSpec extends Specification with DefaultJsonProtocol {
"The FloatJsonFormat" should {
"convert a Float to a JsNumber" in {
4.2f.toJson mustEqual JsNumber(4.2f)
4.2f.toJson.toString mustEqual "4.2"
}
"convert a Float.NaN to a JsNull" in {
Float.NaN.toJson mustEqual JsNull
Expand All @@ -64,13 +65,13 @@ class BasicFormatsSpec extends Specification with DefaultJsonProtocol {
Float.NegativeInfinity.toJson mustEqual JsNull
}
"convert a JsNumber to a Float" in {
JsNumber(4.2f).convertTo[Float] mustEqual 4.2f
"4.2".parseJson.convertTo[Float] mustEqual 4.2f
}
"convert a JsNull to a Float" in {
JsNull.convertTo[Float].isNaN mustEqual Float.NaN.isNaN
"null".parseJson.convertTo[Float].isNaN mustEqual Float.NaN.isNaN
}
}

"The DoubleJsonFormat" should {
"convert a Double to a JsNumber" in {
4.2.toJson mustEqual JsNumber(4.2)
Expand Down