cancel
Showing results for 
Search instead for 
Did you mean: 

Division By 1000 for a double variable

former_member181928
Participant
0 Kudos

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.

Accepted Solutions (0)

Answers (1)

Answers (1)

Former Member
0 Kudos

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

Former Member
0 Kudos

...or alternatively



final BigDecimal d1 = new BigDecimal(22058310.53);
System.out.println("Output Value = " + d1.divide( new BigDecimal(1000), 5, BigDecimal.ROUND_HALF_EVEN));

VS