on 05-29-2006 2:26 PM
Hi all
I have a simple query .
Please follow the following java code
double d1 = 22058310.53;
System.out.println("Output Value = " + d1/1000);
This gives me an output
Output Value = 220583.10530000002
whereas the correct o/p should be 220583.1053
Can anyone pls provide a solution to get the correct result.
regards
NIlesh Taunk.
Hi Nilesh,
First some theory - the range of the real number is infinite and there is no way to fit every possible number into a fixed array of bytes representing double. So in order to overcome that limitation java (and actually every programming language that has fixed size for numbers) is not working with the exact number but with the most close number that fits into the chosen representation. That's why you are seeing that somewhat strange looking result.
How you can fix that ? If your goal is to print 4 numbers after the decimal digit (i.e. you don't care about the rounding errors that are after the fourth digit) you can do it in the following way :
System.out.format("%.4f", d1/1000);
That is JDK 5.0, if you are using 1.4 you can achieve in the following way
java.text.DecimalFormat formatter = new DecimalFormat("0.0000");
System.out.println (formatter.format(d1/1000));
That is only if you are concerned with the output of your double values, if you are looking for some high precision arithmetic (for example the comparison 22058.31053 == 22058310.53/1000 will be false on most JDK-s and on all if you use the strictfp modifier), so if your goal is to perform such evaluations I would advise looking at the package java.math and the classes there or perhaps looking for some more advanced math package.
HTH
Peter
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
85 | |
10 | |
10 | |
9 | |
7 | |
6 | |
5 | |
5 | |
4 | |
3 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.