Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to fix double precision issue in java [duplicate]

Possible Duplicate:
Java floats and doubles, how to avoid that 0.0 + 0.1 + … + 0.1 == 0.9000001?

How can I overcome the precision issue with double multiplication in java android??Please note that I am converting a string value into double value.

eg: when I multiply two double value:

double d1 = Double.valueOf("0.3").doubleValue() * Double.valueOf("3").doubleValue();
System.out.println("Result of multiplication : "+d1);

I am getting the following result : 0.8999999999999999

Some of the results that i am getting are.

0.6*3=1.7999999999999998;
0.2*0.2=0.04000000000000001;
etc.

Instead of the above results I would like to get the following results.

0.3*3=0.9;
0.6*3=1.8;
0.2*0.2=0.04;

Please remember that I am not trying to round it to the nearest integer.

like image 905
prajul Avatar asked Jun 15 '26 14:06

prajul


2 Answers

You should really be using java.math.BigDecimal to avoid any precision issues, and always use a BigDecimal(String) constructor.

BigDecimal result = new BigDecimal("0.3").multiply( new BigDecimal("3.0") );
like image 86
Strelok Avatar answered Jun 18 '26 02:06

Strelok


The problem isn't with multiplication. It starts with Double.valueOf("0.3"). That value can't be represented exactly in floating-point. You should use java.math.BigDecimal, and you should also Google for a page entitled "What every computer scientist should know about floating point".

like image 24
user207421 Avatar answered Jun 18 '26 04:06

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!