Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我使用的数据具有固定的 5 位精度。我想在生成 JsNumber 时强制执行此操作,以便浮点不准确性永远不会生成任何 .123450000000000001 输出。
这可能吗?我还没有找到一种方法来做到这一点。
您可以定义一个自定义JsonWriter来执行此操作(在您的协议内或具有更高优先级隐式范围的其他任何地方):
JsonWriter
implicit object RoundedDoubleJsonWriter extends JsonWriter[Double] { def write(d: Double) = JsNumber(BigDecimal(d).setScale(4, BigDecimal.RoundingMode.HALF_UP) }
根据口味更改舍入模式/方法。