从货币格式的字符串中获取双精度值

Get double value from currency frormatted string

我在我的应用程序中使用 NumberFormat 来获取货币格式的字符串。就像如果用户在该字段中输入 12.25 那么它将根据语言环境更改为 $12.25。这里的语言环境是 en-US。 现在我想将 12.25 值作为格式化字符串的双精度值。 为此,我使用了:

NumberFormat.getCurrencyInstance().parse(".25").doubleValue();

上一行给出了我的要求 12.25 的结果。但是假设用户将他的区域设置更改为其他内容 en-UK。现在,对于上述语言环境,上面的语句给了我 parseException。因为对于语言环境 en-UK,货币字符串 $12.25 不可解析。

那么有什么方法可以从货币格式的字符串中获取双精度值而不管语言环境是什么?

怎么样

new Double(NumberFormat.getCurrencyInstance().parse(".25").doubleValue());

你也可以使用

Double.valueOf() 创建一个 Double 对象,因此 .doubleValue() 应该不是必需的。

还有Double.parseDouble(NumberFormat.getCurrencyInstance().parse(".25"));

可以工作

我不知道下面的解决方案是否完美,但它符合我的要求。

try {
    return NumberFormat.getCurrencyInstance().parse(currency).doubleValue();
} catch (ParseException e) {
    e.printStackTrace();
    // Currency string is not parsable
    // might be different locale
    String cleanString = currency.replaceAll("\D", "");
    try {
        double money = Double.parseDouble(cleanString);
        return money / 100;
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
return 0;

下面是一个可能对您有所帮助的小算法:

public static void main(String[] args)  {

        String cash = "R,000.75"; //The loop below will work for ANY currency as long as it does not start with a digit
        boolean continueLoop = true;

                char[] cashArray = cash.toCharArray();      

        int cpt = 0;

                while(continueLoop){
                    try  
                    {  
                        double d = Double.parseDouble(cashArray[cpt]+"");  
                        continueLoop = false;
                    }catch(NumberFormatException nfe){  
                        cpt += 1;  
                    }
                }

                System.out.println(cpt);

                //From here you can do whatever you want....

                String extracted = cash.substring(cpt);

                NumberFormat format = NumberFormat.getInstance(Locale.US); //YOUR REQUIREMENTS !!!! lol
                try {
                    Number youValue = format.parse(extracted);
                    System.out.println(youValue.doubleValue());
                } catch (ParseException ex) {
                    //handle your parse error here
                }

    }

你应该在输出中得到结果:

2

1000.75