seba123neo
seba123neo

Reputation: 4748

Format Float to n decimal places

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

.

Upvotes: 238

Views: 403405

Answers (11)

user13855328
user13855328

Reputation:

You can use Decimal format if you want to format number into a string, for example:

String a = "123455";
System.out.println(new 
DecimalFormat(".0").format(Float.valueOf(a)));

The output of this code will be:

123455.0

You can add more zeros to the decimal format, depends on the output that you want.

Upvotes: 0

Padmal
Padmal

Reputation: 478

I was looking for an answer to this question and later I developed a method! :) A fair warning, it's rounding up the value.

private float limitDigits(float number) {
    return Float.valueOf(String.format(Locale.getDefault(), "%.2f", number));
}

Upvotes: 4

Arve
Arve

Reputation: 8128

You may also pass the float value, and use:

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

Documentation

Upvotes: 596

Ethan Johnson
Ethan Johnson

Reputation: 21

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;
}

Upvotes: 2

FBB
FBB

Reputation: 1465

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));

Upvotes: 16

Tony L.
Tony L.

Reputation: 19406

Here's a quick sample using the DecimalFormat class mentioned by Nick.

float f = 12.345f;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(df.format(f));

The output of the print statement will be 12.35. Notice that it will round it for you.

Upvotes: 6

M. Usman Khan
M. Usman Khan

Reputation: 4418

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();
    }

Upvotes: 2

Robin Davies
Robin Davies

Reputation: 7827

Kinda surprised nobody's pointed out the direct way to do it, which is easy enough.

double roundToDecimalPlaces(double value, int decimalPlaces)
{
      double shift = Math.pow(10,decimalPlaces);
      return Math.round(value*shift)/shift;
}

Pretty sure this does not do half-even rounding though.

For what it's worth, half-even rounding is going to be chaotic and unpredictable any time you mix binary-based floating-point values with base-10 arithmetic. I'm pretty sure it cannot be done. The basic problem is that a value like 1.105 cannot be represented exactly in floating point. The floating point value is going to be something like 1.105000000000001, or 1.104999999999999. So any attempt to perform half-even rounding is going trip up on representational encoding errors.

IEEE floating point implementations will do half-rounding, but they do binary half-rounding, not decimal half-rounding. So you're probably ok

Upvotes: 5

Anupam
Anupam

Reputation: 517

Try this this helped me a lot

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

Result will be roundfinalPrice --> 5652.26

Upvotes: 18

n3utrino
n3utrino

Reputation: 2381

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.

Upvotes: 1

Nick Campion
Nick Campion

Reputation: 10479

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

Upvotes: 38

Related Questions