2

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?

rich
  • 18,987
  • 11
  • 75
  • 101
  • Would new Integer(String) work? If it throws an exception, you could try another option – Erik Nov 07 '18 at 17:02
  • As a general rule, your life will almost certainly be much simpler if you just stick to one numeric type. If you've got a String that can represent an arbitrary decimal number, use `BigDecimal` instead of trying to switch between `int`, `BigInteger`, `long`, `double`, `BigDecimal`. Trying to switch types adds complexity that almost never actually gives meaningful benefit. – Louis Wasserman Nov 07 '18 at 19:15

3 Answers3

3

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?

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
0

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
}
forpas
  • 160,666
  • 10
  • 38
  • 76
0

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130