Display a value with the non-zero cents and using Float?

Asked

Viewed 132 times

1

Is there any way to make the pennies not cut with float type?

I am converting a value to be formatted with Decimalformat so that it looks like the pennies this way:

    Float numero = 2564786549.87543771885808f;
    DecimalFormat df = new DecimalFormat("0.00");  
    System.out.println(df.format(numero));

I need to be shown this:

2564786432,54

Only this way you’re zeroing out the pennies, you’d be able to keep it?

Ps.: I cannot use double.

  • 1

    For coins, it is recommended to use Bigdecimal, or you will have disadvantages (or your customer rs) because float and double are terrible when it comes to decimal accuracy.

  • 2

    Taking advantage of the previous comment, check based on Bigdecimal the formatting you want. http://stackoverflow.com/questions/5195837/format-float-to-n-decimal-places

  • I’ll switch to this one, wait.

  • 1

    You can’t even use double, nor float. This is a mistake that you can’t fix without using the right guy, even if it looks like you did and that’s a danger because it’s easy to make it look like you did.

  • Okay, got it... I’ve never used Bigdecimal before

1 answer

1

Hello, I recommend reading Formatting Numeric Print Output will be useful!

Excerpt from the source: These methods, format and printf, are equivalent to one other!

import java.util.Calendar;
import java.util.Locale;

public class TestFormat {

    public static void main(String[] args) {
      long n = 461012;
      System.out.format("%d%n", n);      //  -->  "461012"
      System.out.format("%08d%n", n);    //  -->  "00461012"
      System.out.format("%+8d%n", n);    //  -->  " +461012"
      System.out.format("%,8d%n", n);    // -->  " 461,012"
      System.out.format("%+,8d%n%n", n); //  -->  "+461,012"

      double pi = Math.PI;

      System.out.format("%f%n", pi);       // -->  "3.141593"
      System.out.format("%.3f%n", pi);     // -->  "3.142"
      System.out.format("%10.3f%n", pi);   // -->  "     3.142"
      System.out.format("%-10.3f%n", pi);  // -->  "3.142"
      System.out.format(Locale.FRANCE,
                        "%-10.4f%n%n", pi); // -->  "3,1416"

      Calendar c = Calendar.getInstance();
      System.out.format("%tB %te, %tY%n", c, c, c); // -->  "May 29, 2006"

      System.out.format("%tl:%tM %tp%n", c, c, c);  // -->  "2:34 am"

      System.out.format("%tD%n", c);    // -->  "05/29/06"
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.