Java – get different results when rounding decimals

double radius = 5;
double radius = 5;
double area = Math.PI * Math.pow(radius,2);            
// System.out.println(area);

BigDecimal bd = new BigDecimal(area).setScale(2,HALF_UP);
// BigDecimal bd = new BigDecimal(area).setScale(2,ROUND_HALF_UP);
System.out.println(bd.toString());

The output above prints 78.54, but if I perform the same operation through the calculator (Windows Calc interface), the output is 78.57 (i.e. 22 / 7 * 25)

Why do inconsistencies occur

Solution

Do you use 22 / 7 as an approximation of Pi? Because 22 / 7 is 3.142857142857... Where Pi is about 3.14159 This explains your rounding inconsistency

The approximate value of PI used in the JVM is recorded in here According to Javadoc, it is:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>