How to set the precision of JsNumber output in spray.json?

380 views Asked by At

The data I work with has a fixed 5 digits of precision. I'd like to enforce this when generating the JsNumber's so that i.e. floating point inaccuracies would not generate any .123450000000000001 output, ever.

Is this possible? I haven't found out a way to do it.

1

There are 1 answers

1
Matt Enright On

You can define a custom JsonWriter to do this (within your protocol or wherever else with a higher-precedence implicit scope):

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

Change the rounding mode/method to taste.