So I have a double set to equal 1234, I want to move a decimal place over to make it 12.34
So to do this I multiply .1 to 1234 two times, kinda like this
double x = 1234;
for(int i=1;i<=2;i++)
{
x = x*.1;
}
System.out.println(x);
This will print the result, "12.340000000000002"
Is there a way, without simply formatting it to two decimal places, to have the double store 12.34 correctly?
Best Answer
If you use
double
orfloat
, you should use rounding or expect to see some rounding errors. If you can't do this, useBigDecimal
.The problem you have is that 0.1 is not an exact representation, and by performing the calculation twice, you are compounding that error.
However, 100 can be represented accurately, so try:
which prints:
This works because
Double.toString(d)
performs a small amount of rounding on your behalf, but it is not much. If you are wondering what it might look like without rounding:prints:
In short, rounding is unavoidable for sensible answers in floating point whether you are doing this explicitly or not.
Note:
x / 100
andx * 0.01
are not exactly the same when it comes to rounding error. This is because the round error for the first expression depends on the values of x, whereas the0.01
in the second has a fixed round error.prints
NOTE: This has nothing to do with randomness in your system (or your power supply). This is due to a representation error, which will produce the same outcome every time. The precision of
double
is limited and in base 2 rather than base 10, so numbers which can be precisely represented in decimal often cann't be precisely represented in base 2.