3

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.

Elad Benda
  • 35,076
  • 87
  • 265
  • 471

2 Answers2

1

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.
Delan Azabani
  • 79,602
  • 28
  • 170
  • 210
0

try using DecimalFormatter

        float f= 3.44f;                 
        DecimalFormat df = new DecimalFormat("00.##");    
        System.out.println("formatted  value::"+ df.format(f));

============================================================================== updated your function

private static String padWithZeroRightToPeriod(String serverFormat, float unformattedNumber) {
        DecimalFormat df = new DecimalFormat(serverFormat);    
        return df.format(unformattedNumber);
    }

calling function

padWithZeroRightToPeriod("00.##",3.44f)
upog
  • 4,965
  • 8
  • 42
  • 81