| Author |
Issue : Double.parseDouble for 12 digits
|
no one noone
Greenhorn
Joined: Mar 26, 2003
Posts: 3
|
|
I'm running the below code and finding a very peculiar results. For val=123456789123.12345 the output is 1.2345678912312344E11. I didn't expect 12344E11 here. However for val=123456789123.56789 the output is 1.2345678912356789E11, which is fine. Well, i wish the output could be 1.2345678912312345 for input val =123456789123.12345. This issue looks applicable only where there are more than 12 digits prior to decimal places and 12345 after decimal places. Ranchers please rescue. Any suggestions or work around would be deeply appreciated. public class MathRoundTest { public static void main(String [] args) { String val = "123456789123.12345"; try { double v = Double.parseDouble(val); System.out.println("value: " + v); }catch(Exception e){ e.printStackTrace(); } } } [ November 20, 2007: Message edited by: Desmin Josuva ]
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12950
|
|
The floating point types float and double have limited precision. A 12-digit number cannot be represented precisely with a double, so it's not strange that you're seeing rounding errors. If you need to work with arbitrary precision numbers, use BigDecimal instead of double.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Winston Gutkowski
Bartender
Joined: Mar 17, 2011
Posts: 4901
|
|
no one noone wrote:This issue looks applicable only where there are more than 12 digits prior to decimal places and 12345 after decimal places.
No, it has to do with the fact that there are more than 15 digits total.
double supports up to 15 digits of precision (and actually, darn near 16); and precision doesn't care where the decimal point is.
For more details, have a look at the floating point spec.
Winston
|
Isn't it funny how there's always time and money enough to do it WRONG?
|
 |
 |
|
|
subject: Issue : Double.parseDouble for 12 digits
|
|
|