This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Java in General and the fly likes Issue : Double.parseDouble for 12 digits Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Issue : Double.parseDouble for 12 digits" Watch "Issue : Double.parseDouble for 12 digits" New topic
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
    
    3

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
    
    7

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?
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Issue : Double.parseDouble for 12 digits
 
Similar Threads
a little BigInteger problem
Error from sudoku class
Correctly specified Identifiers
ASCII TO EBCDIC conversion preserving COMP-3
working with doubles and strings