将字符串行3.14M转换为Long

use*_*380 -1 java

我有一个尝试将字符串转换为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这样的输入所以我必须删除小数后的数字(我不想这样)

met*_*bed 6

使用java.math.BigDecimal而不是a Long.这将保留小数部分.

注意:不要使用浮动或双重.在解析字符串值时,您可能会遇到奇怪的精度问题.