Shorter

    One of the colleagues needed to print 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. My other colleague was deeply thinking about how to help him ... After 10 minutes, they threw a dozen options, of course, comparing whose faster. In the end, they found a quick solution, but it seemed to us not enough. "Come on, who is shorter!" As a result, we spent half a day profitably, focusing on a fairly concise version. But the light of hope smolders in the heart that it will be possible to save a couple more bytes of precious disk space.

    I don’t want to immediately lay out our version, or rather two, I'll write for now
    how many characters did
    33

    excluding function descriptions and return. Roughly speaking, a solution is a set of operators making $ a (the number to be converted) and $ b (the number of digits in the integer part) a certain $ c, the requirements for which are described above.

    Of course, it will be interesting to consider solutions in other languages.

    UPD Please note that the number of digits in the integer part is a variable. And the fact that there may be a fractional part,
    sscanf('%0'.$b.'d', $a); 
    
    not suitable.

    UPD2. As can be seen from the comments, many decisions are given for a specific case or do not solve the problem properly. For some, the task initially seemed trivial, so it picked up the minuses. But it was still interesting to read your suggestions. Generally speaking, we ourselves accidentally deceived: our 33-byte solution was tested not as a function result, but simply as a transformation:

    for(;strlen($a|0)<$b--;$a="0$a");
    

    Therefore, the task must still be considered along with the return:

    for(;strlen($a|0)<$b--;$a="0$a");return $a;
    

    This is currently the shortest option - 43 bytes. Although, dna turned out to be very close too , but with a retour, it turns out 45.

    If someone breaks up, come up with check numbers:
    foreach (
        array(
            0,      // 000
            .1,     // 000.1
            1,      // 001
            1.2,    // 001.2
            12,     // 012
            12.3,   // 012.3
            123,    // 123
            123.4,  // 123.4
            12345,  // 12345
            12345.6 // 12345.6
        ) as $n)
    {
        echo foo($n, 3), '
    '; }


    I hope everyone now understands what is required in the task, and that you will not be so ruthless :)

    Also popular now: