Java NumberFormat无法解析带有货币国际符号的金额

问题描述 投票:1回答:1

我需要使用货币的国际符号而不是货币的符号解析金额,然后提取金额。也就是说,我需要解析14.00 USD而不是* $ ** 14.00 *或* 14.00 ** CAD *而不是*** $ ** 14.00 *。为此,我放置了以下代码,例如:

NumberFormat.getCurrencyInstance(Locale.forLanguageTag("en-CA")).parse("14.00 CAD").doubleValue();

上面的代码片段引发异常java.text.ParseException: Unparseable number,因为通过getCurrencyInstance()获得的DecimalFormat期望货币字符串以$$-开头。我很难相信NumberFormat不能处理合法的货币字符串,例如14.00 CAD;更可能的是,我还没有找到正确使用它的方法。那么如何解析具有货币国际符号14.00 CAD的金额?

java locale currency
1个回答
0
投票

我相信您要从字符串中获取的只是金额。

您可以通过以下方式实现它:

public class Main {
    public static void main(final String[] args) {
        String strAmount="14.00 CAD".replaceAll("[^\\d.]+", "");
        double amount=Double.parseDouble(strAmount);
        System.out.println(amount);

        strAmount="14.00 USD".replaceAll("[^\\d.]+", "");
        amount=Double.parseDouble(strAmount);
        System.out.println(amount);

        strAmount="$14.00".replaceAll("[^\\d.]+", "");
        amount=Double.parseDouble(strAmount);
        System.out.println(amount);
    }
}

输出:

14.0
14.0
14.0
© www.soinside.com 2019 - 2024. All rights reserved.