GenuineSounds icon

String to smallest Number possible.

GenuineSounds | PRO | 02/12/15 12:57:21 PM UTC | 0 ⭐ | 607 👁️ | Never ⏰ | []
Java |

1.44 KB

|

None

|

0 👍

/

0 👎

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);
    }
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎