Scala Doubles, and Precision

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

    You may use implicit classes:

    import scala.math._
    
    object ExtNumber extends App {
      implicit class ExtendedDouble(n: Double) {
        def rounded(x: Int) = {
          val w = pow(10, x)
          (n * w).toLong.toDouble / w
        }
      }
    
      // usage
      val a = 1.23456789
      println(a.rounded(2))
    }
    

提交回复
热议问题