0

I am using the code snip from spray json deserialize in my scala code. https://github.com/spray/spray-json

import spray.json._
import DefaultJsonProtocol._

object MyJsonProtocol extends DefaultJsonProtocol {
   implicit object RoundedDoubleJsonWriter extends JsonWriter[Double] {
      def write(d: Double) =
         JsNumber(BigDecimal(d).setScale(4, BigDecimal.RoundingMode.HALF_UP))
   }
}

import MyJsonProtocol._
scala> val d = 1234.8473245.toJson
json: spray.json.JsValue = 1234.8473

When I was executing it in command prompt then I am not getting any exception but while executing complete scala code getting the NumberFormatException.

ERROR JobManagerActor: [akka://JobServer/user/jobManager-eb-a124-c7330743f884] - Got Throwable
java.lang.NumberFormatException
at java.math.BigDecimal.<init>(BigDecimal.java:494)
at java.math.BigDecimal.<init>(BigDecimal.java:824)
at scala.math.BigDecimal$.decimal(BigDecimal.scala:52)
at scala.math.BigDecimal$.apply(BigDecimal.scala:249)

Please provide me any example to reproduce above exception and resolve technique?

I found some question in stack overflow related to it and try to reproduce above exception.

scala> val a = BigDecimal("0")
a: scala.math.BigDecimal = 0

scala> val a = BigDecimal("0 ")
java.lang.NumberFormatException
  at java.math.BigDecimal.<init>(BigDecimal.java:494)
  at java.math.BigDecimal.<init>(BigDecimal.java:383)
  at java.math.BigDecimal.<init>(BigDecimal.java:806)
  at scala.math.BigDecimal$.exact(BigDecimal.scala:125)
  at scala.math.BigDecimal$.apply(BigDecimal.scala:283)
  ... 43 elided

but it is not throwing any exception for above code.

sk1007
  • 571
  • 3
  • 11
  • 30

1 Answers1

1

This issue is caused by:def write(d: Double) =, t's value is Double.NaN, when BigDecimal is converting this, NumberFormatException is throwed. Reproduce:

  def main(args: Array[String]): Unit = {
    val t: Double = Double.NaN
    convert(t)
  }
  def convert(d: Double): BigDecimal = {
    println(java.lang.Double.toString(d))
    BigDecimal(d)
  }

For the solution, I think maybe you can handle the Double.NaN when you get it.

chengpohi
  • 14,064
  • 1
  • 24
  • 42