Scala Doubles, and Precision

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

    Recently, I faced similar problem and I solved it using following approach

    def round(value: Either[Double, Float], places: Int) = {
      if (places < 0) 0
      else {
        val factor = Math.pow(10, places)
        value match {
          case Left(d) => (Math.round(d * factor) / factor)
          case Right(f) => (Math.round(f * factor) / factor)
        }
      }
    }
    
    def round(value: Double): Double = round(Left(value), 0)
    def round(value: Double, places: Int): Double = round(Left(value), places)
    def round(value: Float): Double = round(Right(value), 0)
    def round(value: Float, places: Int): Double = round(Right(value), places)
    

    I used this SO issue. I have couple of overloaded functions for both Float\Double and implicit\explicit options. Note that, you need to explicitly mention the return type in case of overloaded functions.

提交回复
热议问题