Advertisement
GenuineSounds

String to smallest Number possible.

Feb 12th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. public static Number convertToSmallestNumber(String input) {
  2.     // Is a decimal number.
  3.     if (input.contains(".")) {
  4.         // Fix no leading zero
  5.         if (input.startsWith("."))
  6.             input = "0" + input;
  7.         // Fix no trailing zero
  8.         if (input.endsWith("."))
  9.             input = input + "0";
  10.         try {
  11.             Float fValue = Float.parseFloat(input);
  12.             // Check for loss of precision with floats, if none return it.
  13.             if (fValue.toString().equals(input))
  14.                 return fValue;
  15.             Double dValue = Double.parseDouble(input);
  16.             // Check for loss of precision with floats, if none return it.
  17.             if (dValue.toString().equals(input))
  18.                 return dValue;
  19.         }
  20.         catch (NumberFormatException e) {}
  21.         // Biggest Number there is for decimals.
  22.         return new BigDecimal(input);
  23.     }
  24.     try {
  25.         Long value = Long.decode(input);
  26.         // Check Byte first since it's the smallest
  27.         if (value.longValue() >= Byte.MIN_VALUE && value.longValue() <= Byte.MAX_VALUE)
  28.             return Byte.decode(input);
  29.         // Next in line
  30.         else if (value.longValue() >= Short.MIN_VALUE && value.longValue() <= Short.MAX_VALUE)
  31.             return Short.decode(input);
  32.         // Next in line
  33.         else if (value.longValue() >= Integer.MIN_VALUE && value.longValue() <= Integer.MAX_VALUE)
  34.             return Integer.decode(input);
  35.         // It must be a Long then
  36.         return value;
  37.     }
  38.     catch (NumberFormatException e) {
  39.         // If it's not a BigInteger then just throw the error because the string was broken as fuck.
  40.         return new BigInteger(input);
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement