Scala Doubles, and Precision

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

    For those how are interested, here are some times for the suggested solutions...

    Rounding
    Java Formatter: Elapsed Time: 105
    Scala Formatter: Elapsed Time: 167
    BigDecimal Formatter: Elapsed Time: 27
    
    Truncation
    Scala custom Formatter: Elapsed Time: 3 
    

    Truncation is the fastest, followed by BigDecimal. Keep in mind these test were done running norma scala execution, not using any benchmarking tools.

    object TestFormatters {
    
      val r = scala.util.Random
    
      def textFormatter(x: Double) = new java.text.DecimalFormat("0.##").format(x)
    
      def scalaFormatter(x: Double) = "$pi%1.2f".format(x)
    
      def bigDecimalFormatter(x: Double) = BigDecimal(x).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble
    
      def scalaCustom(x: Double) = {
        val roundBy = 2
        val w = math.pow(10, roundBy)
        (x * w).toLong.toDouble / w
      }
    
      def timed(f: => Unit) = {
        val start = System.currentTimeMillis()
        f
        val end = System.currentTimeMillis()
        println("Elapsed Time: " + (end - start))
      }
    
      def main(args: Array[String]): Unit = {
    
        print("Java Formatter: ")
        val iters = 10000
        timed {
          (0 until iters) foreach { _ =>
            textFormatter(r.nextDouble())
          }
        }
    
        print("Scala Formatter: ")
        timed {
          (0 until iters) foreach { _ =>
            scalaFormatter(r.nextDouble())
          }
        }
    
        print("BigDecimal Formatter: ")
        timed {
          (0 until iters) foreach { _ =>
            bigDecimalFormatter(r.nextDouble())
          }
        }
    
        print("Scala custom Formatter (truncation): ")
        timed {
          (0 until iters) foreach { _ =>
            scalaCustom(r.nextDouble())
          }
        }
      }
    
    }
    

提交回复
热议问题