1

I want to format a floating number, like this :

  • Input : 1.7
  • output : 01.70

I have already tried below function.

sprintf("%02.02f", 1.7);

Please help.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
Rukmi Patel
  • 2,619
  • 9
  • 29
  • 41

3 Answers3

4

Try:

sprintf('%05.2f', 1.7);

Explanation

This forum post pointed me in the right direction: The first number does neither denote the number of leading zeros nor the number of total charaters to the left of the decimal seperator but the total number of characters in the resulting string!

Example sprintf('%02.2f', 1.7); yields at least the decimal seperator "." plus at least 2 characters for the precision. Since that is already 3 characters in total, the %02 in the beginning has no effect. To get the desired "2 leading zeros" one needs to add the 3 characters for precision and decimal seperator, making it sprintf('%05.2f', 1.7);

Chetan Ameta
  • 7,696
  • 3
  • 29
  • 44
1

Are you tried with str_pad()? It's for strings, and that's what you need, because $var = 001 is an octal and $var = "001" is a string.

   $input = 1.7;
   $output = str_pad($input, "0", 2, STR_PAD_BOTH)
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
1

Try this

sprintf('%05.2f', 1.7);
Ninju
  • 2,522
  • 2
  • 15
  • 21