zeroise()
云策文档标注
概述
zeroise() 是 WordPress 核心函数,用于在数字前添加前导零,以确保数字达到指定长度。它基于 sprintf 实现,根据阈值参数决定是否添加零。
关键要点
- 函数用途:为数字添加前导零,常用于格式化输出,如日期、评论数等。
- 参数说明:$number 为要处理的数字,$threshold 指定数字的最小位数,若数字位数不足则补零。
- 返回值:返回字符串,包含可能添加前导零后的数字。
- 实现方式:使用 sprintf 格式化字符串,格式为 '%0' . $threshold . 's'。
- 相关函数:在 WP_Locale、导出选项、列表表等多个核心功能中被调用。
代码示例
function zeroise( $number, $threshold ) {
return sprintf( '%0' . $threshold . 's', $number );
}注意事项
- 若数字位数已大于或等于阈值,则不会添加零,直接返回原数字字符串。
- 示例:zeroise(10, 4) 返回 '0010',zeroise(5000, 4) 返回 '5000'。
- 用户贡献笔记中提供了实际应用示例,如格式化评论数。
原文内容
Add leading zeros when necessary.
Description
If you set the threshold to ‘4’ and the number is ’10’, then you will get back ‘0010’. If you set the threshold to ‘4’ and the number is ‘5000’, then you will get back ‘5000’.
Uses sprintf to append the amount of zeros based on the $threshold parameter and the size of the number. If the number is large enough, then no zeros will be appended.
Parameters
$numberintrequired-
Number to append zeros to if not greater than threshold.
$thresholdintrequired-
Digit places number needs to be to not have zeros added.
Source
function zeroise( $number, $threshold ) {
return sprintf( '%0' . $threshold . 's', $number );
}
Changelog
| Version | Description |
|---|---|
| 0.71 | Introduced. |
Skip to note 2 content
Codex
Leading zeros on number of comments
$comno = get_comments_number(); echo zeroise( $comno, 2 );