【问题标题】:Restricting decimal places in an array限制数组中的小数位
【发布时间】:2023-07-17 06:39:01
【问题描述】:

目前,这个数组的输出有一个太大的小数位轨迹。我怎样才能将其限制为小数点后 2 位?我的意思是数组'percentage1'。我在网上看到过方法,但我不明白如何将这些方法实现到代码中,如下所示。

int[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};
int[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0};

    double[] percentage1 = new double[correct1.length];
    for(int a = 0; a < correct1.length; a++ ){ 
             percentage1[a] = (((double)correct1[a] / (correct1[a] + incorrect1[a]))*100);
        }

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: java android arrays decimal-point


    【解决方案1】:

    请尝试添加DecimalFormat 对象。

    1. 将此添加到循环的开头,它声明了您要查找的格式 - 2 位小数:DecimalFormat df = new DecimalFormat("#.##");

    2. 使用format 对其进行格式化,然后将其转换回双精度。你需要恢复它的原因是format返回一个字符串。

      percentage1[a] = Double.valueOf(df.format((((double)correct1[a] / (correct1[a] + wrong1[a]))*100)));

    见下面的修改代码:

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] correct1 = {20, 20, 13, 15, 22, 18, 19, 21, 23, 25};
        int[] incorrect1 = {2, 1, 5, 2, 2, 5, 8, 1, 0, 0};
    
            double[] percentage1 = new double[correct1.length];
            DecimalFormat df = new DecimalFormat("#.##");
            for(int a = 0; a < correct1.length; a++ ){ 
                     percentage1[a] = Double.valueOf(df.format((((double)correct1[a] / (correct1[a] + incorrect1[a]))*100)));
                     System.out.println(percentage1[a]);
                }
    
    }
    

    示例结果:

    90.91
    95.24
    72.22
    88.24
    91.67
    78.26
    70.37
    95.45
    100.0
    100.0
    

    【讨论】:

    • 不起作用。尝试检查 mod 0.01 的所有值。如果该方法有效,它们都应该为零。他们不会的。所有这些都比以前不那么准确了。此答案使用 DecimalFormat 但 also 使用 (n/100)*100 技巧,这是多余的。
    【解决方案2】:

    你不能。双打没有小数位。他们有二进制的地方。如果您想要小数位,则必须使用小数基数,即由DecimalFormatBigDecimal 创建的字符串。

    证明here

    【讨论】: