1. Member
Join Date
Feb 2008
Posts
13
Rep Power
0

## Java Algorithm problems?

Right, since im a newbie in java please be nice :)

Look at following 2 statements in java code:
Java Code:
```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)```
i've been told that the above situation happens because of floating points and computer calculations and not an error.

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...

2. 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. ;)

3. Member
Join Date
Feb 2008
Posts
13
Rep Power
0
Whats VM????? :confused:

4. 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.

5. 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);

java(dot)sun(dot)com/j2se/1.5.0/docs/api/java/io/PrintStream.html#printf(java.lang.String,%20java.l ang.Object...)

Alan.

7. 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!!!

Alan.

8. Oki, don't worry in near future we may be fix that issue. You know that, at the time we are discussing this.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•