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)?