Issue converting decimal (Double) value from JSON to case class

Viewed 35

I am using Scala 2.12 with circe version 0.14.1. I am converting a JSON into corresponding case class as below:

case class Document(curr: String, value: Double)
val json = s"""{"Document":{"curr":"USD","value":40000000.01}}"""
import io.circe.generic.auto._
io.circe.parser.decode[Document](json)

The converted case class is below:

Document(USD,4.000000001E7)

I do not want the Double value to change into a Exponential representation. I need it to remain as Double unchanged as

40000000.01

.

1 Answers

You can override toString implementation to see pain instead of engineering notation:

case class Document(curr: String, value: Double) {
  override def toString: String = 
    s"Document($curr,${BigDecimal(value).underlying().toPlainString})"
}

If you want JSON serialization in the plain notation then use the following encoder:

  implicit val doubleE5r: Encoder[Double] = new Encoder[Double] {
    override def apply(a: Double): Json =
      Json.fromJsonNumber(JsonNumber.fromDecimalStringUnsafe(BigDecimal(a).underlying().toPlainString))
  }
Related