【问题标题】:How can I obtain the first 2 decimal places of a number without considering the weight of successive decimal places in Java?如何在不考虑 Java 中连续小数位的权重的情况下获得数字的前 2 位小数?
【发布时间】:2015-02-14 16:33:56
【问题描述】:

在 Java 中,我有一个可以有十进制数字的 Number 对象。

例如,它可能类似于:123.456789

其中 123 是我的号码的整数部分,456789 是小数部分。

好的。如何在不考虑连续小数位的权重的情况下获得仅前 2 位小数的相同数字。

例如,如果我想要只有前 2 位小数的数字,我想要获得 123.45 而不是 123.46(近似值,因为以下小数位大于 5)。

如果我有一个整数 3,我还需要它的前 2 个小数位,即 3.00

我该怎么做?

【问题讨论】:

    标签: java bigdecimal


    【解决方案1】:

    试试下面的 setScale 方法

    BigDecimal value = new BigDecimal("123.456789");
    BigDecimal bg2 = value.setScale(2, RoundingMode.DOWN);
    System.out.println(bg2);
    
    Output:
    123.45
    
    For input as 3, output is 3.00
    

    【讨论】:

      【解决方案2】:
      DecimalFormat decimalFormat = new DecimalFormat("#.##");
      decimalFormat.setRoundingMode(RoundingMode.DOWN);
      decimalFormat.format(123.456789);
      

      输出:123.45

      输入为3,输出为3

      【讨论】:

        猜你喜欢
        • 2020-08-10
        • 2020-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-04
        • 2022-01-03
        • 1970-01-01
        相关资源
        最近更新 更多