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

阿拉伯语系统下捕获经纬度触发java.lang.NumberFormatException求助

问题解决:阿拉伯语系统下经纬度解析的NumberFormatException

问题根源

问题出在区域设置(Locale)不统一:

  • 存储经纬度时,DecimalFormat默认使用系统当前Locale(阿拉伯语),生成了阿拉伯数字(如٣٨.٦٣٤);
  • 解析时用Double.parseDouble(),它依赖系统默认Locale,阿拉伯语环境下无法正确识别阿拉伯数字或英文格式的小数点,导致解析失败。

正确解决方案

存储和解析时强制固定使用英文Locale,彻底脱离系统区域的影响:

1. 存储经纬度(格式化时指定Locale)

修改格式化代码,创建DecimalFormat时传入英文区域的符号集:

if (longitude != 0.0 && latitude != 0.0) {
    // 固定使用英文Locale,确保生成英文数字和小数点
    DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(Locale.ENGLISH);
    DecimalFormat formatter = new DecimalFormat("##0.00##", symbols);
    UserConfig.getSingleton().setLongitude(formatter.format(longitude));
    UserConfig.getSingleton().setLatitude(formatter.format(latitude)); 
}

2. 解析经纬度(解析时指定Locale)

不要直接用Double.parseDouble(),改用指定Locale的NumberFormat解析,避免依赖系统区域:

NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.ENGLISH);
try {
    this.longitude = numberFormat.parse(UserConfig.getSingleton().getLongitude()).doubleValue();
    this.latitude = numberFormat.parse(UserConfig.getSingleton().getLatitude()).doubleValue();
} catch (ParseException e) {
    // 处理解析失败的异常,比如设置默认值或报错提示
    e.printStackTrace();
    this.longitude = 0.0;
    this.latitude = 0.0;
}

为什么之前转成"38.634"仍报错?

阿拉伯语Locale下,Double.parseDouble()会遵循阿拉伯语的数字解析规则,此时英文小数点.可能不被识别为有效的小数分隔符(部分阿拉伯语区域用逗号作为分隔符),必须明确指定Locale才能统一解析逻辑。

内容的提问来源于stack exchange,提问作者The Artist For Informatics

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:18:09