0

I am trying to display float variable upto two digits of precision. Suppose the variable is 50.35 then it is getting displayed. But when the variable is 50.30 it is displaying only 50.3. Unable to make it to display 50.30.

Jens
  • 67,715
  • 15
  • 98
  • 113
Trooper
  • 145
  • 3
  • 15

3 Answers3

6

Try with:

 System.out.printf("%.2f\n", 50.30);

Where you use a format string telling printf to print the number following floating point format with 2 as the number of decimal digits printed.

Here You can find a table with the supported converters and format flags you can use with printf as well as with other format methods.

2

You may use DecimalFormat for this.

DecimalFormat dformat = new DecimalFormat();
dformat.setMaximumFractionDigits(2);
System.out.println(dformat.format(decimalNumber));
Macrosoft-Dev
  • 2,195
  • 1
  • 12
  • 15
1

You mean you want to format the floating point values. You can do this using

 String text = String.format("%.2f", v);

or

 System.out.printf("%.2f\n", 50.3); // prints 50.30

or use DecimalFormat.

BTW make sure you are using double as it has better precision than float

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130