1
votes

Using the standard Java Double class to parse a floating point number with mantissa seems to omit the + sign from the exponent.

For example:

Double.parseDouble("1258124354E-28") returns 1.258124354E-19, but
Double.parseDouble("1243544322E+24") returns 1.243544322E33 (not E+33)

Is there any way to get the + sign using Double, without string post-processing?

The BigDecimal class does a better job, e.g.

new BigDecimal("1243544322E+24").toString() does return 1.243544322E+33

but it is generally slower than Double, which shows in intensive processing.

2
Don't print it with toString, use an instance of NumberFormat. - John Watts

2 Answers

6
votes

You need to differentiate between the value stored in a double and its string representation.

A double doesn't store a textual representation at all. 1.243544322E33 is 1.243544322E+33. They're the same value.

Now if you want to work on how you format a double value back to a String, that's a different matter - but the parsing you're doing is fine. You're not losing any information.

2
votes

Jon is correct as above, its representing it correctly in memory. If you want it to display with the + on the mantissa then you are talking about string formatting the double.

Long winded official formatter reference

import java.util.Formatter;

double myDouble = Double.parseDouble("1243544322E+24");

Formatter formatter = new Formatter();
formatter.format("%+E", myDouble); //This should return with what you want, though with an extra + infront of the number

I haven't ran this code so I'm not 100% sure it will do the job. The + in the format specifier forces it to place a + or - sign for any number... I believe that extends to the mantissa.