0

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.

akauppi
  • 17,018
  • 15
  • 95
  • 120

1 Answers1

3

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.

Matt Enright
  • 7,245
  • 4
  • 33
  • 32
  • Thanks, it worked. But it took me some hours to realize this only works for `Double` if you use `Float` the precision goes away. Thanks. – Montenegrodr Mar 27 '18 at 15:03