Java Algorithm problems?
Right, since im a newbie in java please be nice :)
Look at following 2 statements in java code:
i've been told that the above situation happens because of floating points and computer calculations and not an error.
System.out.println(456.8 + 0.09); //456.89 (WORKS as expected)
System.out.println(23.4 + 0.09); //23.49 (WORKS as expected)
System.out.println(1.8 + 0.09); //1.8900.....01 (DOESNT WORK as expected)
So what i want to discuss is that how do i rectify it? And what is the best way to solve it so that i want 1.89 to be displayed instead of ...
Im writing a calculator so i need 1.89 to be displayed on screen rather than 1.8900..01. Currently those display values are held in a variable of double.
DO i change it to float or something else so that it can accept a bigger range?
Any help would be greatful! Thanks in advance...
In default if you use a decimal number VM take it as a double value. If you define them as a float value, you get the correct value.
And see the number of decimal you get, in your code. ;)
VM - Virtual Machine (java virtual machine normally call like that)
There are several ways to format the values of float and doubles for display using java classes. For example DecimalFormat
If you read your text you should see that double has a larger range than float. But your problem is displaying the value, so you need to format it to what you want to see.
You can use System.out.printf to format numbers. This would leave off the last few decimal positions.
System.out.printf("%10.5f\n", 1.8 + .09);
Hey Alan, can't you add links in such situations. :) It's better to add a link to the URL when you posting links.
As long as the OP can find his way to the reference I wanted him to see.
I am told I can't post links or images - so I posted the link my way!!!
Oki, don't worry in near future we may be fix that issue. You know that, at the time we are discussing this.