Hi,
What am I doing wrong here:
Here is my example example:
double test = 0.05 + 0.1;
This outputs: 0.15000000000000002
Obviously the answer should be 0.15, what am I doing wrong?
Printable View
Hi,
What am I doing wrong here:
Here is my example example:
double test = 0.05 + 0.1;
This outputs: 0.15000000000000002
Obviously the answer should be 0.15, what am I doing wrong?
you're doing nothing wrong. Please search and read up on floating point numeric representation and digital computers. Note that this is not a Java issue, but a general digital computation issue.
OK thanks, I thought it was something to do with this, so is there any way to solve this problem?
No real solution to solve. You can round the value or you can create some kind of fraction class if it's that important.
For me, the problem is not so much with the number itself but with the display of the number as a String. Often the solution is to format the String so that it's to your liking, and two common ways to do this is with String.format (or printf), or by using a DecimalFormat object. For instance:
Code:import java.text.DecimalFormat;
public class Fubar
{
public static void main(String[] args)
{
double test = 0.05 + 0.1;
System.out.println(test);
System.out.println(String.format("%.2f", test));
System.out.printf("%.2f%n", test);
DecimalFormat df = new DecimalFormat("0.00");
System.out.println(df.format(test));
}
}
Thanks!
Is df.format parsing the double into a String, the same as Double.toString() say but rounded off?
I've read around and seen articles saying don't use float/double for money, so what type is actually reccomended?
Thanks for the solution anyway it's appreciated, I went with String.format!
In general you should not use float for much of anything as it has a lower accuracy than double, but neither are very good for money, much for the reason shown in your initial post. They are not 100% accurate, and when dealing with money, especially large amounts, you really need 100% accuracy. fishtoprecords, a very knowledgeable regular here, will tell you that you should use a number not subject to rounding errors seen with float or double. Instead consider using decimal numeric types such as int, long, or BigDecimal or BigInteger. Money is often represented numerically by moving the decimal point over to the right two spaces so that there is no decimal component. Thus 100.00 dollars becomes 10000 cents. Then do all the calculations with cents and only convert back to dollars when displaying the results.