Format Float to n decimal places

375,485

Solution 1

You may also pass the float value, and use:

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

Documentation

Solution 2

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

Solution 3

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

Solution 4

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

Solution 5

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.

Share:
375,485

Related videos on Youtube

seba123neo
Author by

seba123neo

Android Developer VB6, VB .NET, C#, Java Amateur Astronomer and Astrophotographer

Updated on July 08, 2022

Comments

  • seba123neo
    seba123neo almost 2 years

    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

    .

  • Zach L
    Zach L about 13 years
    +1. Here's the Android-specific documentation,which should be essentially the same.
  • seba123neo
    seba123neo about 13 years
    but I need the result is a float number, not a string.
  • seba123neo
    seba123neo about 13 years
    but I need the result is a float number, not a string.
  • Nick Campion
    Nick Campion about 13 years
    Are you saying you want to round the float? Normally the only time precision of a float matters is for display.
  • n3utrino
    n3utrino about 13 years
    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.
  • seba123neo
    seba123neo about 13 years
    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
    seba123neo about 13 years
    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.
  • Gerard
    Gerard almost 11 years
    This is more useful for those looking to round and do some further computations with it, otherwise, Arve's answer is probably best.
  • Gomino
    Gomino about 8 years
    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);
  • FBB
    FBB almost 8 years
    Of note, use of DecimalFormat constructor is discouraged, see my answer for a correct use of NumberFormat.
  • FBB
    FBB almost 8 years
    Of note, use of DecimalFormat constructor is discouraged, see my answer for a correct use of NumberFormat.
  • ZhaoGang
    ZhaoGang about 7 years
    this answer gives a String value, not a Float value, I don't think a good answer.
  • Mark Buikema
    Mark Buikema about 7 years
    Why would you force a dot as separator?
  • xeruf
    xeruf over 6 years
    I've also used this method for a while, but I would think that pow is a too expensive operation to use for rounding?
  • Robin Davies
    Robin Davies over 6 years
    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().
  • Tjaart
    Tjaart over 6 years
    @MarkBuikema I think there are cases where it would be absolutely necessary, such as when compiling document formats driven by standards, eg. PDF documents.
  • Shiva Krishna Chippa
    Shiva Krishna Chippa about 6 years
    This is not working when (for example) floatValue = 8.499. It is giving 8.5.
  • FBB
    FBB almost 6 years
    @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.
  • AlexV
    AlexV over 5 years
    This works with GWT as well. String.format() - does not.
  • NateS
    NateS over 2 years
    DecimalFormat#format takes a double, making the formatted float have more digits than a float can hold.
  • VanessaF
    VanessaF about 2 years
    This answer does not create a float