public static Number toNumber ( String string ) { BigDecimal value = new BigDecimal ( string ) ; try { long l = value . longValueExact ( ) ; int i = ( int ) l ; if ( ( long ) i == l ) { return i ; } else { return l ; } } catch ( ArithmeticException e ) { double d = value . doubleValue ( ) ; if ( BigDecimal . valueOf ( d ) . equals ( value ) ) { float f = ( float ) d ; if ( ( double ) f == d ) { return ( float ) d ; } else { return d ; } } else { return null ; } } }
There must be a better way .