Scala Doubles, and Precision

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

    How about :

     val value = 1.4142135623730951
    
    //3 decimal places
    println((value * 1000).round / 1000.toDouble)
    
    //4 decimal places
    println((value * 10000).round / 10000.toDouble)
    

提交回复
热议问题