【问题标题】:Only 2 digit after decimal point without last 2 digit rounding off in java小数点后只有 2 位数字,Java 中没有最后 2 位四舍五入
【发布时间】:2018-11-30 10:55:44
【问题描述】:

我尝试只保留小数点后的 2 位数字,而在 java 中没有最后 2 位数字舍入。 这是我的代码:-

val df = DecimalFormat("#.##")
val gh = df.format(19.14966566)

df 的ans = 19.15

但我只想要 19.14,因为它是 19.14966566 的最后 2 位数,没有四舍五入

【问题讨论】:

标签: android kotlin decimal decimalformat


【解决方案1】:

你可以使用下面的代码

double x = 19.14966566;
double y = Math.floor(x * 100) / 100;
O/P-> 19.14

在你的代码风格中

val df = 19.14966566
val gh = Math.floor(x * 100) / 100
gh-> 19.14

您也可以参考此链接:https://stackoverflow.com/a/32303271/6838146

如果您遇到任何问题,请告诉我

【讨论】:

    【解决方案2】:

    你可以试试这个……它对我有用……

    val df = DecimalFormat("#.##")
    df.roundingMode = RoundingMode.FLOOR
    val gh = df.format(19.14966566)
    

    【讨论】:

      【解决方案3】:

      NumberFormat 为您提供更多解决方案。
      使用NumberFormat,您可以显式设置:

      • 语言环境
      • 小数位数的最小值
      • 最大小数位数
      • 舍入模式

      像这样:

      val nf = NumberFormat.getInstance(Locale.US)
      
      nf.minimumFractionDigits = 2
      nf.maximumFractionDigits = 2
      nf.roundingMode = RoundingMode.DOWN
      
      val gh = nf.format(19.14966566)
      println(gh)
      

      将打印:

      19.14
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-12
        • 2012-01-03
        • 2012-07-26
        • 1970-01-01
        • 2015-11-24
        相关资源
        最近更新 更多