# mutliplicatio of double values

• 04-13-2009, 01:44 PM
katkamravi
mutliplicatio of double values
hi all,
i have a problem in multiplication of double values.

double d1=0.99;
double d2=d1*3;

d2 should contain 2.97 but i m getting 2.9699999999999998
can anybody tell me why its giving me such a huge value...
• 04-13-2009, 02:09 PM
dswastik
Use NUmberFormatter class for this
Code:

``` import java.text.*; class A{ public static void main(String[] arg){                 double d1=0.99;                 double d2=d1*3;                 System.out.println("unformatted result="+d2);                 NumberFormat nf=new DecimalFormat("#0.00");                 String formatted=nf.format(d2);                 System.out.println("formatted result="+formatted);         } }```
• 04-13-2009, 02:28 PM
neilcoffey
Floating point values that cannot be made by adding powers of 2 cannot be stored completely accurately. So, for example, 0.5 can be stored accurately, because it's 1/2; 0.125 can be stored accurately, because it's 1 / (2 * 2 * 2); 0.75 can be stored accurately, because it's (1/2 + 1/(2*2)). In each case, either the number is 1 divided by 2 multiplied together some number of times, or else you can get to the number by adding such fractions together.

But in the case of 2.97, there's no such series of fractions that can be added together to get to *exactly* 2.97. So what gets stored is whatever series of such fractions there is that comes closest to 2.97. (There's actually an extra complication: the number of 2s multiplied together have to be more-or-less near to one another.) Anyway, the upshot is, that there are lots of numbers (actually, most numbers in the universe) that cannot be expressed completely accurately by a floating point number. What you end up with is, say, 2.97 accurate to within 14 or so digits, which is what you're seeing printed out.

The answer is usually not to worry about it, but to treat it as a printing problem. So when you print out a floating point number, you can explicitly format it to so many decimal places. For example:

Code:

`System.out.println(String.format("%.3f", number));`
here, the "%.3f" means "a floating-point number to 3 decimal places".