【问题标题】:How can I specify the number of decimal places of a BigDecimal to print?如何指定要打印的 BigDecimal 的小数位数?
【发布时间】:2011-05-26 08:33:10
【问题描述】:

我使用BigDecimal如下:

BigDecimal val = object.getValue();//it returns BigDecimal type value

val 包含 12.2300。我想在我的页面上显示 12.23。我该怎么做?

【问题讨论】:

标签: java bigdecimal


【解决方案1】:

使用DecimalFormat:

String formatted = new DecimalFormat("#.##").format(val);

【讨论】:

    【解决方案2】:

    您可以使用 DecimalFormat,也可以使用字符串操作对其进行操作

            public static String format(BigDecimal big, int precision){
                String bigS = big.toString();
                int index = bigS.indexOf('.');
                String add = bigS.substring(index, index + precision + 1);
                String formatted = big.longValue() + "" + add;
    
                return formatted;
            }
    
            public static void main(String[] args) {
    
                BigDecimal big = new BigDecimal(2342342232.23232);
                System.out.println(format(big, 2));
                System.out.println(format(big, 3));
            }
    

    当然,DecimalFormat 是一种聪明的方式

    【讨论】:

    • 根本不应该依赖toString()。 ;)
    猜你喜欢
    • 2017-07-26
    • 1970-01-01
    • 2021-08-30
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2022-07-08
    相关资源
    最近更新 更多