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

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

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;
}

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

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

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

How about this:

  1. function generateReceiptNumber(int $id)
  2. {
  3. while($id>=100000000)
  4. $id -= 100000000 - 1;
  5. return sprintf('%06d', $id);
  6. }

答案2

得分: 0

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

  1. // 使用取模运算将 ID 限制在范围 0 到 99,999,999
  2. $limited_id = $id % 100000000;
  3. // 使用前导零格式化限制后的 ID,确保至少有 6 位数字
  4. $receipt_number = sprintf('%06d', $limited_id);
  5. return $receipt_number;

}

英文:
  1. public static function generateReceiptNumber(int $id)
  2. {
  3. // Handle the special case when $id is 100000000
  4. if ($id === 100000000) {
  5. return '000001';
  6. }
  7. // Use modulo to limit the ID to the range 0 to 99,999,999
  8. $limited_id = $id % 100000000;
  9. // Format the limited ID with leading zeros to ensure at least 6 digits
  10. $receipt_number = sprintf('%06d', $limited_id);
  11. return $receipt_number;
  12. }

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:

确定