I have a method which tries to convert strings into long:
public static Long getLong(String str) {
long multiplier = 1;
try {
Long value = -1L;
str = str.replaceAll("\\s", ""); // remove whitespace
str = str.replaceAll("%", "");
str = str.replaceAll(",", "");
if (str.contains("M")) {
str = str.replaceAll("M", "");
multiplier = 1000000;
} else if (str.contains("B")) {
str = str.replaceAll("B", "");
multiplier = 1000000000;
} else if (str.contains("K")){
str = str.replaceAll("K", "");
multiplier = 1000;
}
// an exception is thrown for values like 199.00, so removing
// decimals if any
str = str.contains(".") ? str.substring(0, str.lastIndexOf(".")) : str;
value = Long.valueOf(str);
value = value * multiplier;
return value;
} catch (Exception e) {
throw new RuntimeException(str + " cannot be parsed into long value");
}
This method works fine values like "1K", "300M", "2B", "0" but not for the values like 3.14M or 1.1K. As mentioned in above comment Long.valueOf(str) throws exception if it has to take a input like 1.24 so I have to remove the digits after decimal (which I don't want to)