How can I tell if a decimal number represented as a String will fit in a double?

Viewed 172

I'm parsing a String value which I know contains a number.

If it only contains digits and it's between Integer.MIN_VALUE and Integer.MAX_VALUE I'm parsing it as an int, similarly for long otherwise I'm using BigInteger.

If it contains a decimal value I'd either like to parse it as a double or as a BigDecimal.

Can I test if the numeric value in the String "fits" into a double and is therefore safe to parse as a double, or whether it needs to be held in a BigDecimal to prevent loss of precision?

3 Answers

and is therefore safe to parse as a double, or whether it needs to be held in a BigDecimal to prevent loss of precision?

This won't be the answer that you're looking for, but since you seem to be concerned about loss of precision, you should use a BigDecimal in place of any double.

The number 0.1 can fit in a double, but it isn't precise (as 0.1 can not be represented accurately in binary).

See: Is floating point math broken?

The Double class contains these constants:

public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324
public static final double MAX_VALUE = 0x1.fffffffffffffP+1023; // 1.7976931348623157e+308

you could use them to perform your checks if you can.
But wouldn't it be easier just a try/catch block:

String str = "1234567890";
double number = 0;
try {
    number = Double.parseDouble(str);
} catch (NumberFormatException e) {
    e.printStackTrace();
    // put extra code here
}

I would parse it as a BigDecimal and then check whether double can store the value without a loss of information to an acceptable degree.

Related