Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to format a float like 0#.## in java? [duplicate]

I get an input from the user. I want to print it in this format:

0#.##

or

##.##

how do I do this in java?

Today I'm using:

padWithZeroRightToPeriod(product.formats[index],Float.parseFloat(currentPrice));

and

private String padWithZeroRightToPeriod(String serverFormat, float unformattedNumber) {
  int nDigits = getNumberOfDigitsAfterPeriod(serverFormat);
  String floatingFormat = "%4." + nDigits + "f";
  String formattedPrice = String.format(floatingFormat, unformattedNumber);

  return formattedPrice
}

but it converts 08.56 to 8.56.

like image 485
Elad Benda Avatar asked Nov 28 '25 16:11

Elad Benda


1 Answers

For two decimal places, and at least two whole digits, with leading zeroes:

String floatingFormat = "%05.2f";
  • The 0 pads the string with zeros instead of spaces.
  • The 5 is the minimum total field width, including the whole, fractional and decimal point parts.
  • The 2 is the exact number of decimal places to be printed.
like image 160
Delan Azabani Avatar answered Nov 30 '25 06:11

Delan Azabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!