Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static Number convertToSmallestNumber(String input) {
- // Is a decimal number.
- if (input.contains(".")) {
- // Fix no leading zero
- if (input.startsWith("."))
- input = "0" + input;
- // Fix no trailing zero
- if (input.endsWith("."))
- input = input + "0";
- try {
- Float fValue = Float.parseFloat(input);
- // Check for loss of precision with floats, if none return it.
- if (fValue.toString().equals(input))
- return fValue;
- Double dValue = Double.parseDouble(input);
- // Check for loss of precision with floats, if none return it.
- if (dValue.toString().equals(input))
- return dValue;
- }
- catch (NumberFormatException e) {}
- // Biggest Number there is for decimals.
- return new BigDecimal(input);
- }
- try {
- Long value = Long.decode(input);
- // Check Byte first since it's the smallest
- if (value.longValue() >= Byte.MIN_VALUE && value.longValue() <= Byte.MAX_VALUE)
- return Byte.decode(input);
- // Next in line
- else if (value.longValue() >= Short.MIN_VALUE && value.longValue() <= Short.MAX_VALUE)
- return Short.decode(input);
- // Next in line
- else if (value.longValue() >= Integer.MIN_VALUE && value.longValue() <= Integer.MAX_VALUE)
- return Integer.decode(input);
- // It must be a Long then
- return value;
- }
- catch (NumberFormatException e) {
- // If it's not a BigInteger then just throw the error because the string was broken as fuck.
- return new BigInteger(input);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement