Java中的3位小数精度

问题描述 投票:-2回答:2
    Float x = 4;
    Float answer = 4/16;

答案是0.25,但我想显示答案,直到3个小数位,例如0.250

如何实现?请帮忙吗?

java
2个回答
2
投票

要具有十进制精度,请使用BigDecimal类。可以在setScale中指定小数位数,如下所示

BigDecimal a = new BigDecimal("0.25");
a = a.setScale(3, BigDecimal.ROUND_HALF_EVEN);

-1
投票

一种可能的解决方案是使用toString()在小数点处使用split(".")截止。如果结果字符串的长度小于3,则加零直到长度为3。如果大于3,则在此处切断。如:

public String triplePrecision(Float float) {

    String tmp = float.toString();
    int length = tmp.split(".")[1].length();//numbers after decimal

    for (int i = 0; i < 3 - length; i++) {

        tmp += "0"; //appending zeroes

    }

    return tmp.substring(0, indexOf(".") + 3); //start to 3 places after decimal

}

-1
投票

您可以在Java中使用DecimalFormat如下格式化数字,

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(3);
System.out.println(df.format(decimalNumber));
© www.soinside.com 2019 - 2024. All rights reserved.