You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将巴西雷亚尔货币字符串"59000,00"解析为double类型?

解析巴西雷亚尔格式字符串为数值类型的正确方法

嘿,我来帮你搞定这个问题!你当前代码遇到的问题其实很明确:NumberFormat.getCurrencyInstance(Locale) 是专门用来解析**带货币符号(比如巴西的R$)**的字符串的,但你的输入"59000,00"只有数字和小数分隔符,没有货币标识,所以才会触发解析异常。

下面给你两种靠谱的实现方式,顺便提醒一个货币处理的关键注意事项:

方法一:解析纯数字格式的字符串

如果你的输入永远是不带货币符号的数值(比如"59000,00"这种),直接用巴西本地化的通用数字格式就好,它会自动识别逗号作为小数分隔符:

final String price = "59000,00";
final Locale brLocale = new Locale("pt", "BR");

// 获取适配巴西格式的数字解析器
final NumberFormat numberFormat = NumberFormat.getNumberInstance(brLocale);
try {
    final double d = numberFormat.parse(price).doubleValue();
    System.out.println(d); // 输出结果:59000.0
} catch (ParseException e) {
    e.printStackTrace();
}

方法二:兼容带/不带货币符号的场景

如果你的输入可能混合两种情况——有时候带R$符号(比如"R$ 59000,00"),有时候不带,那可以给货币格式设置宽松解析模式,让它忽略缺失的货币符号:

final String price = "59000,00";
final Locale brLocale = new Locale("pt", "BR");

final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(brLocale);
// 开启宽松解析,允许解析不带货币符号的数值
currencyFormat.setLenient(true);
// 明确告诉解析器不要只解析整数部分
currencyFormat.setParseIntegerOnly(false);

try {
    final double d = currencyFormat.parse(price).doubleValue();
    System.out.println(d); // 输出结果:59000.0
} catch (ParseException e) {
    e.printStackTrace();
}

敲黑板:别用double处理货币!

这里必须提醒你,double是浮点数,用来处理货币会有精度丢失的风险(比如0.1 + 0.2的结果并不是精确的0.3)。如果是涉及实际交易的货币计算,强烈建议用BigDecimal,示例如下:

final String price = "59000,00";
final Locale brLocale = new Locale("pt", "BR");

final NumberFormat numberFormat = NumberFormat.getNumberInstance(brLocale);
try {
    // 解析后转成BigDecimal,保证精度不丢失
    final BigDecimal amount = new BigDecimal(numberFormat.parse(price).toString());
    System.out.println(amount); // 输出精确的59000.00
    // 后续的加减乘除等计算都能保证精度
} catch (ParseException e) {
    e.printStackTrace();
}

内容的提问来源于stack exchange,提问作者owl777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:29:55