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
.
I think what you want ist
and use the return value to display.
will always return 625.3 because its mainly used to calculate something.
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
This is a much less professional and much more expensive way but it should be easier to understand and more helpful for beginners.
You may also pass the float value, and use:
String.format("%.2f", floatValue);
Documentation
Of note, use of
DecimalFormat
constructor is discouraged. The javadoc for this class states:https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
So what you need to do is (for instance):