Search code examples
javatypescastingdoublebigdecimal

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


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?


Solution

  • 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?