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

turn a number based on passed in value to at least 6 digit and max 8 digit

提问人:codingDummy 提问时间:8/10/2023 最后编辑:codingDummy 更新时间:8/10/2023 访问量:49

问:

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。

想要实现这一点的目的是因为,我有一个显示文本框,其文本限制只有 8 位,我只能将数字重新启动回000001并继续计数重复。

PHP 数学

评论

0赞 nice_dev 8/10/2023
$id作为数据库增量 ID,不需要您执行这些操作。
0赞 codingDummy 8/10/2023
@nice_dev,我需要这样做,因为增量 ID 会不断增加,同时我的显示值限制最多只能显示 8 位,所以这就是为什么我需要从头开始重新开始显示值的原因
0赞 nice_dev 8/10/2023
那么999999999、99999999、99999999999999、9999999900、65000000000 等应该输出什么?您尚未添加事例和预期的输出。
0赞 codingDummy 8/10/2023
@nice_dev,Olivier 已经整理出了解决方案,我一直在尝试一些数字,它似乎得到了正确的输出,您可以参考它
0赞 nice_dev 8/10/2023
我乐于学习,但前提是有新的东西需要我学习。这些基本的数学知识显然很容易,你只有一个明显正确的答案的原因是因为你有一个不完整的问题。

答:

0赞 Ravi Rathore 8/10/2023 #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;
}

如果对您有所帮助,请查看此答案。

评论

1赞 codingDummy 8/10/2023
感谢您的解决方案。但是,当$id等于 1000000000 时,它将返回 000000 而不是 000001
3赞 Olivier 8/10/2023 #2

这个怎么样:

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

评论

0赞 codingDummy 8/10/2023
这个解决方案太棒了,谢谢。但是,当 $id 等于 999999999 时,它将返回 100000000 而不是 000001
0赞 Olivier 8/10/2023
@codingDummy我更新了代码。
0赞 codingDummy 8/10/2023
出色的解决方案,谢谢巴德。欣赏
0赞 Eng Cy 8/10/2023
绝妙的解决方案,我刚才很努力,但没能成功,我现在学到了一些东西