将基于传入值的数字转换为至少 6 位和最大 8 位

问题描述 投票:0回答:2
public static function generateReceiptNumber(int $id)
{
     $receipt_number = sprintf('%06d', $id % 100000000);
     return $receipt_number;
}

我有上面的代码来帮助我将传入的 $id 转换为最小 6 位数字和最大 8 位数字。例如:000001 - 99999999

但是这段代码有一个缺陷,当 $id 等于 100000000 时,它会返回 000000, 我怎样才能增强上面的代码来给我 000001 呢?

依此类推,$id是数据库增量id

php math modulo
2个回答
1
投票
public static function generateReceiptNumber(int $id)
{
    // Handle the special case when $id is 100000000
    if ($id === 100000000) {
        return '000001';
    }

    // Use modulo to limit the ID to the range 0 to 99,999,999
    $limited_id = $id % 100000000;
    
    // Format the limited ID with leading zeros to ensure at least 6 digits
    $receipt_number = sprintf('%06d', $limited_id);
    
    return $receipt_number;
}

请检查此答案是否对您有帮助。


0
投票
public static function generateReceiptNumber(int $id)
{
     return str_pad((string)$id,6,"0",STR_PAD_LEFT);
}

此方法没有上限,如果确实需要,只需添加一个条件即可实现

© www.soinside.com 2019 - 2024. All rights reserved.