我有一个尝试将字符串转换为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");
}
Run Code Online (Sandbox Code Playgroud)
此方法可以使用"1K","300M","2B","0"等精细值,但不适用于3.14M或1.1K等值.正如上面提到的注释Long.valueOf(str)抛出异常,如果它必须采取像1.24这样的输入所以我必须删除小数后的数字(我不想这样)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |