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.
I want to format a floating number, like this :
I have already tried below function.
sprintf("%02.02f", 1.7);
Please help.
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);
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)
Try this
sprintf('%05.2f', 1.7);