Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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

1 Answer

0 votes
by (46k points)

You may also allow the float value, and try:

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

Here's the Documentation

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 26, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
asked Apr 14, 2021 in Java by Jake (7k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.6k answers

500 comments

108k users

Browse Categories

...