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?
No - if you want to store decimal values accurately, use
BigDecimal
.double
simply can't represent a number like 0.1 exactly, any more than you can write the value of a third exactly with a finite number of decimal digits.This is caused by the way computers store floating-point numbers. They don't do so exactly. As a programmer, you should read this floating-point guide to familiarize yourself with the trials and tribulations of handling floating-point numbers.
if it's just formatting, try printf
output