Santosh Pillai Santosh Pillai - 7 months ago 20
PHP Question

number_format and sprintf for same variable

How can I have two leading zeros and two decimal places for the same number. I tried the code below but only number_format or sprintf seems to work (they don't seem to work together)

sprintf("%04d", number_format((float)$height, 2, '.', ''))


The above code returns 0025 instead of 0025.00

Answer

%d is for integers. Use %f for float:

%0        7        .2       f
 padding  TOTAL    decimal  float
 char     string   digits   type
          length

In your case:

sprintf( '%07.2f', (float) $height );

Output:

0025.00
Comments