我是Java的新手,我在与DecimalFormat的任务中遇到问题

当我给出整数时,它不应有任何小数,
如果我给出十进制数字,则应打印十进制值

我使用了DecimalFormater如下

DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance();
decimalFormat.setMaximumFractionDigits(2);
decimalFormat.applyPattern("0");

System.out.println(decimalFormat.format(123456789.2569));


这是不带小数的打印。
我用我的模式代替
decimalFormat.applyPattern("#.##");

在这种情况下,我给299
它正在打印3

但它应该打印299
怎么做?

最后,如果我给265应该是265,如果我给265.36应该是265.36

最佳答案

如果使用#.##模式,则将仅获得第一个数字,其余数字将被视为小数位。

这就解释了为什么输入3时得到299的原因,因为在这种模式下,299被视为2.99,然后四舍五入为3

因此,请尝试使用此模式:

decimalFormat.applyPattern("###.##");


有关它的更多信息,请查看:


Customizing Formats in Documentation
Java DecimalFormat | tutorials.jenkov.com

10-07 19:18
查看更多