236

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

.

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90
seba123neo
  • 4,688
  • 10
  • 35
  • 53

11 Answers11

590

You may also pass the float value, and use:

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

Documentation

Tenfour04
  • 83,111
  • 11
  • 94
  • 154
Arve
  • 8,058
  • 2
  • 22
  • 25
  • 75
    Please be carefull as String.format depend on your current Local configuration, you may not get a dot as a separator. Prefer using `String.format(java.util.Locale.US,"%.2f", floatValue);` – Gomino Mar 02 '16 at 16:31
  • 7
    this answer gives a String value, not a Float value, I don't think a good answer. – ZhaoGang Mar 17 '17 at 08:21
  • 3
    Why would you force a dot as separator? – Mark Buikema Mar 23 '17 at 10:55
  • 1
    @MarkBuikema I think there are cases where it would be absolutely necessary, such as when compiling document formats driven by standards, eg. PDF documents. – Tjaart Nov 04 '17 at 09:20
  • This answer does not create a float – VanessaF Apr 02 '22 at 08:58
  • When you try to contain this in a Float object, the precision will be the same as of float only(precision is up to 6 decimal places). For better precision, Double class can be used. – Narendra Rawat Dec 07 '22 at 19:24
38

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

Nick Campion
  • 10,479
  • 3
  • 44
  • 58
  • 1
    +1. Here's the [Android-specific documentation](http://developer.android.com/reference/java/text/DecimalFormat.html),which should be essentially the same. – Zach L Mar 04 '11 at 15:49
  • but I need the result is a float number, not a string. – seba123neo Mar 04 '11 at 18:29
  • Are you saying you want to round the float? Normally the only time precision of a float matters is for display. – Nick Campion Mar 04 '11 at 19:03
  • sorry, you're right, I was confused, just format the number when shown on screen, not before, that was my question, thank you very much, problem solved. – seba123neo Mar 07 '11 at 22:38
  • Of note, use of `DecimalFormat` constructor is discouraged, see my answer for a correct use of `NumberFormat`. – FBB Jun 17 '16 at 10:10
18

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

Dejell
  • 13,947
  • 40
  • 146
  • 229
Anupam
  • 509
  • 1
  • 6
  • 16
  • 2
    This is more useful for those looking to round and do some further computations with it, otherwise, Arve's answer is probably best. – Gerard May 27 '13 at 17:13
  • This works with GWT as well. String.format() - does not. – AlexV Nov 26 '18 at 15:23
16

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));
FBB
  • 1,414
  • 2
  • 17
  • 29
  • This is not working when (for example) floatValue = 8.499. It is giving 8.5. – Shiva Krishna Chippa Mar 19 '18 at 18:45
  • 4
    @ShivakrishnaChippa: yes, because here we specify that we want 2 digits after the comma, and to do a up rounding. In that case, 8.499 is rounded to 8.5. If you want 8.499 to be display, simply set 3 as the maximum fraction digits. – FBB May 18 '18 at 11:55
6

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.

Tony L.
  • 17,638
  • 8
  • 69
  • 66
  • Of note, use of `DecimalFormat` constructor is discouraged, see my answer for a correct use of `NumberFormat`. – FBB Jun 17 '16 at 10:11
5

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

Robin Davies
  • 7,547
  • 1
  • 35
  • 50
  • I've also used this method for a while, but I would think that `pow` is a too expensive operation to use for rounding? – xeruf Oct 27 '17 at 13:56
  • Never optimize until you actually have a performance problem. More important to be right than fast. And I can't honestly imagine an application where performance of controlled rounding would be an issue, unless you were Visa or Mastercard (who would just throw more machines at it). And pow() is probably faster than round(). – Robin Davies Oct 28 '17 at 21:57
2
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();
    }
M. Usman Khan
  • 3,689
  • 1
  • 59
  • 69
2

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;
}
GenuinePlaceholder
  • 685
  • 1
  • 10
  • 25
2

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));
}
Padmal
  • 458
  • 5
  • 15
1

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.

n3utrino
  • 2,361
  • 3
  • 22
  • 32
  • but I need the result is a float number, not a string. – seba123neo Mar 04 '11 at 18:30
  • 2
    if you need a float to show it to the user, there may be something wrong with the design of the application. Usually the float is used to calculate and a string is used to show it to the user. – n3utrino Mar 05 '11 at 08:04
  • sorry, you're right, I was confused, just format the number when shown on screen, not before, that was my question, thank you very much, problem solved. – seba123neo Mar 07 '11 at 22:41
0

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.

  • DecimalFormat#format takes a double, making the formatted float have more digits than a float can hold. – NateS Aug 18 '21 at 01:45