I have a String representation of a primitive and my goal is to determine which primitive is it.
My function is as follows:
public Object getPrimitive(String primitiveAsString) {
.....
}
So for example I would like to return an integer in case the input is "223" but a double if the input is "223.1" or even "223.0"(!!). Moreover, I would like to separate between float and double and even between integer and "BigInteger".
I have tried a solution using NumberFormat and it didn't work for me....
Is there an elegant way to do so?
Thanks!
An idea is just trying to return each type in try-catch.
Code: (the error-checking may be less than ideal)
public static void main(String[] args)
{
System.out.println(getPrimitive("123")); // Byte
System.out.println(getPrimitive("1233")); // Short
System.out.println(getPrimitive("1233587")); // Integer
System.out.println(getPrimitive("123.2")); // Float
System.out.println(getPrimitive("123.999999")); // Double
System.out.println(getPrimitive("12399999999999999999999999")); // BigInteger
System.out.println(getPrimitive("123.999999999999999999999999")); // BigDecimal
}
static public Object getPrimitive(String string)
{
try { return Byte.valueOf(string); } catch (Exception e) { };
try { return Short.valueOf(string); } catch (Exception e) { };
try { return Integer.valueOf(string); } catch (Exception e) { };
try { return new BigInteger(string); } catch (Exception e) { };
try { if (string.matches(".{1,8}"))
return Float.valueOf(string); } catch (Exception e) { };
try { if (string.matches(".{1,17}"))
return Double.valueOf(string); } catch (Exception e) { };
try { return new BigDecimal(string); } catch (Exception e) { };
// more stuff ?
return null;
}
The reasoning behind .{1,8}
and .{1,17}
is that float
and double
are accurate to about 7 and 16 digits each (according to some random source). .
is a wild-card. {x,y}
means repeated between x and y times.
EDIT:
Improved to differentiate float
, double
and BigDecimal
with a basic regex among other things.