2

我的应用程序中有以下代码行,可以将我的百分比四舍五入到合理的长度;

double percentage = ((double)correct*100)/((double)total);
DecimalFormat df = new DecimalFormat("#.0");
percentage = Double.valueOf(df.format(percentage));

这段代码在 99% 的情况下都运行良好,但是当来自一些欧洲国家的人们使用它时会崩溃,给我一个NumberFormatException.

这是因为当DecimalFormat舍入 double时56.7777,会将其舍入56,8(用逗号),这意味着当我尝试将其转换为 double 时,会引发 NumberFormatException。

有什么方法可以设置一个位置,DecimalFormat这样我就知道它总是会四舍五入56.8而不是56,8

4

5 回答 5

2

使用相同的数字格式解析数据

percentage = df.parse(df.format(percentage), new ParsePosition(0))

其他解决方案是设置自己的格式符号

DecimalFormat df = new DecimalFormat('#.0', new DecimalFormatSymbols())

我推荐第一个解决方案。我在使用逗号作为小数分隔符的语言环境中对其进行了测试。

于 2013-08-22T20:54:48.453 回答
1
    NumberFormat numberFormat = NumberFormat.getNumberInstance(context.getResources().getConfiguration().locale); // Locale.getDefaultLocale()
    DecimalFormat  decimalFormat = (DecimalFormat)numberFormat;
    char separator =decimalFormat.getDecimalFormatSymbols().getDecimalSeparator();
    decimalFormat.applyPattern("#".concat(Character.toString(separator)).concat("0"));"

您需要根据Locale

于 2013-08-22T20:51:51.797 回答
1

问题是您指定了自定义格式,DecimalFormat然后String使用默认指定的格式解析结果Locale

您有几种解决问题的方法:

  1. 使用相同的DecimalFormat对象来格式化和解析数字。

  2. 使用不同的舍入算法。例如:

    double roundToHundredths(double d) {
        return (int)(d * 100) / 100.0;
    }
    
  3. 将数字存储为int“百分之一”。用它进行计算int并将其显示为小数。

  4. 用于BigDecimal更高的精度。

请注意,在任何进一步的计算中使用“四舍五入”数字仍然很棘手,因为浮点数不精确。这意味着“四舍五入”的结果不一定准确。

于 2013-08-22T21:03:01.263 回答
0

您可以为测试值设置货币,然后格式化并查找是否有逗号或 . 并适当处理,如果,

DecimalFormat 测试 = new DecimalFormat("0.00"); test.setCurrency(c);

字符串 testsample = test.format(1.23); char ch = sample.indexOf(".") > 0 ? “。” :“,”;

于 2013-08-22T20:53:48.683 回答
0

将小数转换为字符串并将其应用于它

str = str.replaceAll(",","."); // or "\\.", it doesn't matter...

它会,变成.

于 2013-08-22T20:57:06.617 回答