search

Home  >  Q&A  >  body text

Method to encapsulate numbers into 6 to 8 character limit

<p><br /></p> <pre class="brush:php;toolbar:false;">public static function generateReceiptNumber(int $id) { $receipt_number = sprintf(' d', $id % 100000000); return $receipt_number; }</pre> <p>I am using the above code to convert the incoming $id to a minimum 6 digit, maximum 8 digit number. For example: 000001 - 99999999</p> <p>But there is a flaw in this code. When $id equals 100000000, it will return 000000. How should I improve the above code to return 000001? </p> <p>By analogy, $id is the auto-incremented ID of the database. </p> <p>The reason I want to achieve this is because I have a display text box with a text limit of only 8 digits and I can only count the numbers back up from 000001 and keep repeating. </p>
P粉315680565P粉315680565518 days ago613

reply all(2)I'll reply

  • P粉403804844

    P粉4038048442023-08-11 09:20:43



    
    
    public static function generateReceiptNumber(int $id)
    {
        // 处理特殊情况,当$id为100000000时     if ($id === 100000000) {
            return '000001';
        }
    
        // 使用取模运算将ID限制在范围0到99,999,99     $limited_id = $id % 100000000;
        
        // 格式化限制的ID,使用前导零确保至少6位     $receipt_number = sprintf('%06d', $limited_id);
        
        return $receipt_number;
    }
    


    Please see if this answer helps

    reply
    0
  • P粉863295057

    P粉8632950572023-08-11 00:36:54

    How about this:

    function generateReceiptNumber(int $id)
    {
        while($id>=100000000)
            $id -= 100000000 - 1;
        return sprintf('%06d', $id);
    }

    reply
    0
  • Cancelreply