Results 1 to 3 of 3
Thread: mutliplicatio of double values
 04132009, 01:44 PM #1Member
 Join Date
 Apr 2009
 Posts
 3
 Rep Power
 0
 04132009, 02:09 PM #2Senior Member
 Join Date
 Dec 2008
 Location
 Kolkata
 Posts
 286
 Rep Power
 12
Use NUmberFormatter class for this
Java 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); } }
 04132009, 02:28 PM #3Senior Member
 Join Date
 Nov 2008
 Posts
 286
 Rep Power
 12
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 moreorless 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:
Java Code:System.out.println(String.format("%.3f", number));
Neil Coffey
Javamex  Java tutorials and performance info
Similar Threads

nonstatic method add(double,double) cannot be referenced from a static context
By cravi85 in forum Java SoftwareReplies: 5Last Post: 03212009, 09:32 PM 
Double
By Xystus777 in forum New To JavaReplies: 2Last Post: 01212009, 10:39 AM 
Double.valueOf() vs Double.parseDouble()
By greenbean in forum New To JavaReplies: 10Last Post: 01122009, 08:39 AM 
Retaining DB values as well as Dynamically generated Values.. Help Needed !
By rajivjha in forum Advanced JavaReplies: 0Last Post: 05222008, 10:53 AM 
Accessing boolean Values of another values in one class.
By a_iyer20 in forum Advanced JavaReplies: 4Last Post: 04152008, 01:04 PM
Bookmarks