【问题标题】:java.text.MessageFormat increase decimal places precision for BigDecimal / Numberjava.text.MessageFormat 增加 BigDecimal / Number 的小数位精度
【发布时间】:2020-12-08 07:14:21
【问题描述】:

我正在使用 java.text.MessageFormat 替换显示单价的模板中的占位符。以下是执行此操作的代码。

public String format(Object[] arguments, String pattern) {
    MessageFormat formatter = new MessageFormat("");
    formatter.applyPattern(pattern);
    return formatter.format(arguments);
}

pattern

{0} {1} 每 {2}

arguments

argument[0] = "USD",argument[1] = BigDecimal(0.0002),argument[2] = "shirt"

我希望格式化程序能够输出

“每件衬衫 0.0002 美元”

但格式化程序正在降低精度并产生

“每件衬衫 0 美元”

看起来 MessageFormat 只考虑小数点后 3 位数字。 “BigDecimal(0.01)”按预期工作。

那么我可以调整任何属性来告诉MessageFormat 它应该使用一定的精度吗?更改 pattern 不是我的选择。

我可以在格式化之前将参数从BigDecimal 转换为String。但这将是我最后的选择。

编辑: 小数点后三位限制来自NumberFormat

private int    maximumFractionDigits = 3; 

有没有办法我们可以改变这个值并让 MessageFormat 使用它?

【问题讨论】:

    标签: java formatting bigdecimal messageformat


    【解决方案1】:

    您可以在模式中使用{0,number,#.##} 等格式。 MessageFormat 的 Javadoc 有更多详细信息,如果您有兴趣。

    由于您无法更改模式,因此事先将对象转换为字符串将是唯一的解决方案

    编辑:实际上我没有意识到可以通过编程方式设置格式:

    public static void main(String[] args) {
        Object[] argument = new Object[3];
        argument[0] = "USD";
        argument[1] = new BigDecimal(0.0002);
        argument[2] = "shirt";
    
        System.out.println(format(argument, "{0} {1} per {2}"));
    }
    
    public static String format(Object[] arguments, String pattern) {
        MessageFormat formatter = new MessageFormat(pattern);
    
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(7);
    
        for (int i = 0; i < arguments.length; i++) {
            if (arguments[i] instanceof BigDecimal) {
                formatter.setFormat(i, nf);
            }
        }
    
        return formatter.format(arguments);
    }
    

    这应该打印:USD 0.0002 per shirt

    【讨论】:

    • 通过预先将对象转换为字符串,我不仅要在很多地方更改代码,而且还会丢失提供的默认数字格式
    • 我明白了,我想您可以使用参数的类来应用格式,请参阅我编辑的答案
    • 完美!正是我想要的
    猜你喜欢
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 2018-06-04
    • 2012-05-26
    • 2013-07-17
    • 2020-07-28
    相关资源
    最近更新 更多