double radius = 5;
double area = Math.PI * Math.pow(radius, 2);
// System.out.println(area);
BigDe开发者_高级运维cimal bd = new BigDecimal(area).setScale(2, HALF_UP);
// BigDecimal bd = new BigDecimal(area).setScale(2, ROUND_HALF_UP);
System.out.println(bd.toString());
The above output gets printed as 78.54, but if I perform the same operation via the calculator (windows calc interface) the output comes out as 78.57 (i.e. 22/7 * 25
).
Why is there an inconsistency
Are you using 22/7
as an approximate value for PI? Because 22/7
is 3.142857142857...
where PI is approximately 3.14159...
. This explains your rounding inconsistencies.
The approximation of PI that is used in the JVM is documented here. According to the JavaDoc, it is:
The double value that is closer than any other to pi
22/7
is approximation to PI
, Its not exact and so the result
Almost completely off-topic (and its javascript). But its still a fun answer for actually visibly seeing PI being calculated.
This method is obviously super-super-slow at calculating PI...but is kinda fun to watch.
(function (t) {
(function () {
var a = 0,
b = 1,
d = 4,
c = ~1e9;
(function p() {
if (!t) {
return;
}
b -= 2;
a -= d / b;
d = -d;
if (++c % 2000 === 0) {
t.innerHTML = a;
setTimeout(p, 13);
} else {
if (c) {
p();
} else {
t.innerHTML = a;
}
}
}());
}());
}(document.getElementById("someplace-to-hold-the-calculation")))
Philippe Leybaert set up a JSBin for it.
精彩评论