简体   繁体   中英

Format fractional percent in java yields very strange behaviour

I am trying to format percentages with the following code:

NumberFormat fmt = NumberFormat.getPercentInstance();
fmt.setRoundingMode(RoundingMode.HALF_UP);
fmt.setMinimumFractionDigits(0);
fmt.setMaximumFractionDigits(0);
System.out.println(fmt.format(0.145));

However, I get a very strange result:

14%

Changing the value 0.145 to something else, for example 0.125 will work properly and the result will be as expected

13%

Can someone shed some light on this? Thanks in advance

This is due to the inherent rounding error in double , resulting in 0.145 being rounded to

0.1449999999999999900079927783735911361873149871826171875

Use BigDecimal if you expect perfect accuracy.

I think that is an result of the intern representation of floats. (Decimal numbers represented by binary numbers).

Your 0.145 might be internally represented as 0.144999999999..., so rounding mode rounds down.

您应该阅读每个计算机科学家应该知道的关于浮点运算的内容 ,但基本上它归结为.145不能在IEEE浮点中精确表示,因此四舍五入到可以表示的最接近的值,恰好小于.145,因此在四舍五入为两位数时会四舍五入。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM