Scala Doubles, and Precision

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

    Edit: fixed the problem that @ryryguy pointed out. (Thanks!)

    If you want it to be fast, Kaito has the right idea. math.pow is slow, though. For any standard use you're better off with a recursive function:

    def trunc(x: Double, n: Int) = {
      def p10(n: Int, pow: Long = 10): Long = if (n==0) pow else p10(n-1,pow*10)
      if (n < 0) {
        val m = p10(-n).toDouble
        math.round(x/m) * m
      }
      else {
        val m = p10(n).toDouble
        math.round(x*m) / m
      }
    }
    

    This is about 10x faster if you're within the range of Long (i.e 18 digits), so you can round at anywhere between 10^18 and 10^-18.

提交回复
热议问题