One of the colleagues needed to display a number with leading zeros to get this:
1 => 001
23 => 023
456 => 456
7.89 => 007.89
12345.6 => 12345.6
In his case, it was required to have at least three digits in the integer part. We with another colleague firmly wondered how to help him ... After 10 minutes, we threw a dozen options, naturally comparing whose faster. In the end, we found a quick solution, but this was not enough for us. "Come on, who has a shorter!" As a result, we spent half a day with benefit, stopping at a rather concise version. But there is a glimmer of hope in the heart that it will be possible to save a couple more bytes of precious disk space.
I do not want to immediately lay out our version, or rather two, I will write while
how many characters did33
without the description of the function and return. Roughly speaking, a solution is a set of operators that make $ a (the number that needs to be converted) and $ b (the number of digits in the integer part) some $ c, the requirements for which are described above.
Of course, it will be interesting to consider solutions in other languages.
')
UPD. Note that the number of digits in the integer part is variable. And the fact that there may be a fractional part,
sscanf('%0'.$b.'d', $a);
does not fit.
UPD2. As can be seen from the comments, many solutions are given for a specific case or do not solve the problem properly. To some, the task initially seemed trivial, so I picked up the minuses. But it was still interesting to read your suggestions. Generally speaking, we ourselves accidentally misjudged: our 33-byte solution was not tested as a result of a function, but simply as a conversion:
for(;strlen($a|0)<$b--;$a="0$a");
Therefore, the task must still be considered with the return:
for(;strlen($a|0)<$b--;$a="0$a");return $a;
At the moment it is the shortest option - 43 bytes. Although,
dna turned out to be very
close too, but with a return it turns out 45.
If someone has a trouble in inventing verification numbers:
foreach ( array( 0,
I hope everyone now understands what is required in the task and that you will not be so ruthless :)