我需要格式化一个浮点数到小数点后n位。

尝试BigDecimal,但是返回值不正确…

public static float Redondear(float pNumero, int pCantidadDecimales) {
    // the function is call with the values Redondear(625.3f, 2)
    BigDecimal value = new BigDecimal(pNumero);
    value = value.setScale(pCantidadDecimales, RoundingMode.HALF_EVEN); // here the value is correct (625.30)
    return value.floatValue(); // but here the values is 625.3
}

我需要返回一个带有我指定的小数点后数位的浮点值。

我需要Float值返回而不是Double

.


当前回答

你也可以传递float值,并使用:

String.format(“%.2f”, floatValue);

文档

其他回答

这是一种不那么专业,也更昂贵的方式,但它应该更容易理解,对初学者更有帮助。

public static float roundFloat(float F, int roundTo){

    String num = "#########.";

    for (int count = 0; count < roundTo; count++){
        num += "0";
    }

    DecimalFormat df = new DecimalFormat(num);

    df.setRoundingMode(RoundingMode.HALF_UP);

    String S = df.format(F);
    F = Float.parseFloat(S);

    return F;
}

我一直在寻找这个问题的答案,后来我发明了一种方法!:)一个公平的警告,它是四舍五入的值。

private float limitDigits(float number) {
    return Float.valueOf(String.format(Locale.getDefault(), "%.2f", number));
}
public static double roundToDouble(float d, int decimalPlace) {
        BigDecimal bd = new BigDecimal(Float.toString(d));
        bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

试试这个,这对我帮助很大

BigDecimal roundfinalPrice = new BigDecimal(5652.25622f).setScale(2,BigDecimal.ROUND_HALF_UP);

结果将是 roundfinalPrice—> 5652.26

值得注意的是,不鼓励使用DecimalFormat构造函数。这个类的javadoc声明:

一般情况下,不要直接调用DecimalFormat构造函数,因为NumberFormat工厂方法可能返回DecimalFormat以外的子类。

https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

所以你需要做的是(例如):

NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
formatter.setRoundingMode(RoundingMode.HALF_UP); 
Float formatedFloat = new Float(formatter.format(floatValue));