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

huangapple go评论101阅读模式
英文:

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

问题

public static function generateReceiptNumber(int $id)
{
$receipt_number = sprintf('%08d', $id % 100000000 + 1);
return $receipt_number;
}

英文:
public static function generateReceiptNumber(int $id)
{
     $receipt_number = sprintf('%06d', $id % 100000000);
     return $receipt_number;
}

I am having the above code to help me to transform a passed in $id to a minimum 6 digit and maximum 8 digit number. eg: 000001 - 99999999

But this code has a flaws that when the $id equal to 100000000, it will return me 000000,
how can i enhance the code above to give me 000001 instead?

So and so forth, the $id is the database incremental id.

The purpose of wanted to achieve this is because, i have a display text box which the text limit is only 8 digit, i can only restarted the number back to 000001 and continue the count to repeat.

答案1

得分: 3

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

How about this:

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

答案2

得分: 0

public static function generateReceiptNumber(int $id)
{
// 处理特殊情况,当 $id 为 100000000 时
if ($id === 100000000) {
return '000001';
}

// 使用取模运算将 ID 限制在范围 0 到 99,999,999
$limited_id = $id % 100000000;

// 使用前导零格式化限制后的 ID,确保至少有 6 位数字
$receipt_number = sprintf('%06d', $limited_id);

return $receipt_number;

}

英文:
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;
}

please check this answer if it will help you.

huangapple
  • 本文由 发表于 2023年8月10日 14:50:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76873240.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定