Format Float to n decimal places

2019-01-01 07:12发布

I need to format a float to "n"decimal places.

was trying to BigDecimal, but the return value is not correct...

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
}

I need to return a float value with the number of decimal places that I specify.

I need Float value return not Double

.

10条回答
回忆,回不去的记忆
2楼-- · 2019-01-01 07:28

I think what you want ist

return value.toString();

and use the return value to display.

value.floatValue();

will always return 625.3 because its mainly used to calculate something.

查看更多
公子世无双
3楼-- · 2019-01-01 07:29

Take a look at DecimalFormat. You can easily use it to take a number and give it a set number of decimal places.

Edit: Example

查看更多
千与千寻千般痛.
4楼-- · 2019-01-01 07:33
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();
    }
查看更多
心情的温度
5楼-- · 2019-01-01 07:34

This is a much less professional and much more expensive way but it should be easier to understand and more helpful for beginners.

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;
}
查看更多
步步皆殇っ
6楼-- · 2019-01-01 07:43

You may also pass the float value, and use:

String.format("%.2f", floatValue);

Documentation

查看更多
皆成旧梦
7楼-- · 2019-01-01 07:43

Of note, use of DecimalFormat constructor is discouraged. The javadoc for this class states:

In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat.

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

So what you need to do is (for instance):

NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
formatter.setRoundingMode(RoundingMode.HALF_UP); 
Float formatedFloat = new Float(formatter.format(floatValue));
查看更多
登录 后发表回答