0

I don't understand the 02 part of the %02.1f additional format value of the sprintf(). I know that .1 is the number of decimal places, but I don't get the 02 part.

echo sprintf('The distance is %02.1f', $this-car->getDistance());

I was looking at https://www.w3schools.com/php/func_string_sprintf.asp and it says that [0-9] "Specifies the minimum width held of to the variable value" but I don't understand what they mean.

Thank you in advance for any info that I could get.

I was looking at w3schools.com and other search results.

user3783243
  • 5,368
  • 5
  • 22
  • 41
gs3
  • 1
  • https://www.php.net/manual/en/function.printf.php – user229044 Apr 14 '23 at 17:57
  • https://www.php.net/manual/en/function.sprintf.php#refsect1-function.sprintf-parameters – aynber Apr 14 '23 at 17:57
  • 1
    https://www.php.net/manual/en/function.sprintf.php - W3 Schools isn't always the best for documentation, but PHP Manual provides it too. – Tim Lewis Apr 14 '23 at 17:58
  • So zero is "Only left-pads numbers with zeros." and if so what the 2 would be? I am not getting that "Only left-pads numbers with zeros." too, if that's what it is. – gs3 Apr 14 '23 at 18:04
  • I was trying this out in my code editor / browser and when I run 05 instead of 02 nothing changes on the screen. The %02.1f thing, what is the 02 part, what does it do? – gs3 Apr 14 '23 at 18:07
  • https://stackoverflow.com/questions/28739818/php-how-to-add-leading-zeros-zero-padding-to-float-via-sprintf/28739819#28739819 might have the information you want, but in short, it's the minimum number of digits on both sides. So `0` will print `0.0`, but `134.24` will print `134.2` – aynber Apr 14 '23 at 18:27

1 Answers1

2

The position that 2 is occupying is the minimum field width - of the whole thing, including both sides of the decimal and the decimal point itself. Since x.y is already three characters, the 2 doesn't do anything here, but you can't include the 0 (which means "pad with zeros") without specifying some value for the field width.

But %05.1 will absolutely produce different results from %02.1 – as long as the number isn't so large that it already takes 5 spaces once you add the decimal to it:

php > sprintf('%02.1f', 0)
0.0
php > sprintf('%05.1f', 0)
000.0

If you leave off the 0, it's still padded, but with spaces:

php > sprintf('%5.1F', 0)
  0.0
Mark Reed
  • 91,912
  • 16
  • 138
  • 175