Scala Doubles, and Precision

前端 未结 12 1275
逝去的感伤
逝去的感伤 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 21:54

    Here's another solution without BigDecimals

    Truncate:

    (math floor 1.23456789 * 100) / 100
    

    Round:

    (math rint 1.23456789 * 100) / 100
    

    Or for any double n and precision p:

    def truncateAt(n: Double, p: Int): Double = { val s = math pow (10, p); (math floor n * s) / s }
    

    Similar can be done for the rounding function, this time using currying:

    def roundAt(p: Int)(n: Double): Double = { val s = math pow (10, p); (math round n * s) / s }
    

    which is more reusable, e.g. when rounding money amounts the following could be used:

    def roundAt2(n: Double) = roundAt(2)(n)
    

提交回复
热议问题