2

I want to print out a decimal number with the following rules:

  • There should always be two digits to the left of the decimal point.
  • There should always be three digits to the right of the decimal point.

So here are some examples of how I want numbers to be displayed:

  • 12.345
  • 02.310
  • 07.499
  • 42.300

I recognize that I could use modulo arithmetic to separate the integral and decimal parts, then format them separately, but that seems messy. I'm hoping there's a simpler solution using sprintf, though I can't seem to get it to work.

I've already tried the following (none of which work):

printf('%02.3f', 2.31); // nope
printf('%5.3f', 2.31);  // nadda
printf('%05.5f', 2.31); // no way
printf('%02d', 2.31);   // obviously not
printf('%03f', 2.31);   // not that either

Is there no clean way to do this? Can I not have my cake (leading zeros) and eat it too (fixed decimal precision at the same time)?

soapergem
  • 9,263
  • 18
  • 96
  • 152

1 Answers1

3

This should work for you:

echo sprintf("%06.3f", 2.31);

Output:

02.310
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` -- it should be `printf()` without `echo` every time. Some explanation would be a bonus too. – mickmackusa Apr 14 '22 at 06:00