Scala Doubles, and Precision

前端 未结 12 1249
逝去的感伤
逝去的感伤 2020-12-12 21:19

Is there a function that can truncate or round a Double? At one point in my code I would like a number like: 1.23456789 to be rounded to 1.23

12条回答
  •  春和景丽
    2020-12-12 22:08

    I wouldn't use BigDecimal if you care about performance. BigDecimal converts numbers to string and then parses it back again:

      /** Constructs a `BigDecimal` using the decimal text representation of `Double` value `d`, rounding if necessary. */
      def decimal(d: Double, mc: MathContext): BigDecimal = new BigDecimal(new BigDec(java.lang.Double.toString(d), mc), mc)
    

    I'm going to stick to math manipulations as Kaito suggested.

提交回复
热议问题