Scala Doubles, and Precision

前端 未结 12 1241
逝去的感伤
逝去的感伤 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:56

    Since no-one mentioned the % operator yet, here comes. It only does truncation, and you cannot rely on the return value not to have floating point inaccuracies, but sometimes it's handy:

    scala> 1.23456789 - (1.23456789 % 0.01)
    res4: Double = 1.23
    

提交回复
热议问题