如何适配不同Locale设置的小数分隔符,保障单元测试跨环境正常运行
问题根因
DecimalFormat 默认使用当前操作系统的 Locale 配置生成格式化字符串,英文 Locale 的小数分隔符是 .,德文 Locale 的小数分隔符是 ,,而 Double.parseDouble 方法仅支持解析 . 作为分隔符的数字字符串,因此德文环境下格式化返回的 0,3225 无法被解析,抛出异常。
解决方案
分两种业务场景选择对应修改方案:
场景1:业务要求返回统一格式的数字字符串(和Locale无关)
直接修改 roundFloat 方法,为 DecimalFormat 指定固定 Locale,强制使用 . 作为小数分隔符,修改后代码如下:
public String roundFloat(int decimalDigits, Number randomValue) { String formatPattern = getFormatPattern(decimalDigits); // 指定Locale为US,固定使用小数点作为小数分隔符,不受系统Locale影响 DecimalFormat decimalFormat = new DecimalFormat(formatPattern, DecimalFormatSymbols.getInstance(Locale.US)); decimalFormat.setRoundingMode(RoundingMode.FLOOR); return decimalFormat.format(randomValue); }
该方案无需修改原有测试代码,即可实现全Locale环境正常运行。
场景2:业务要求roundFloat方法适配不同Locale返回对应格式的字符串
修改测试代码,使用当前Locale对应的NumberFormat解析格式化后的字符串,避免硬编码分隔符的问题,修改后测试代码如下:
@Test public void myTest() throws ParseException { String randomValue = roundFloat(4, 0.32258437873357226); // 用当前系统Locale的数字格式化工具解析,适配不同分隔符 Number parsedValue = NumberFormat.getInstance().parse(randomValue); Assert.assertEquals(parsedValue.doubleValue(), 0.3225); }
内容的提问来源于stack exchange,提问作者Jeff
相关产品推荐
相关产品推荐

