I'm using sprintf() to get a formatted string of some float numbers with a certain precision. In addition, I wanted to add leading zeros to make all numbers even in length. Doing that for integers is pretty straight forward:

我正在使用sprintf()来获取具有一定精度的一些浮点数的格式化字符串。另外,我想添加前导零以使所有数字均匀。对整数执行此操作非常简单:

sprintf('%02d', 1);

This will result in 01. However, trying the same for a float with precision doesn't work:

这将导致01.但是,对具有精度的浮点尝试相同的操作不起作用:

sprintf('%02.2f', 1);

Yields 1.00.

How can I add leading zeros to a float value?

如何将前导零添加到浮点值?

1 个解决方案

#1


20

Short answer: sprintf('%05.2f', 1); will give the desired result 01.00

简答:sprintf('%05.2f',1);将给出所需的结果01.00

Note how %02 was replaced by %05.

请注意%02如何被%05取代。

Explanation

This forum post pointed me in the right direction: The first number does neither denote the number of leading zeros nor the number of total charaters to the left of the decimal seperator but the total number of characters in the resulting string!

这个论坛帖子向我指出了正确的方向:第一个数字既不表示前导零的数量,也不表示小数分隔符左侧的总字符数,而是结果字符串中的字符总数!

Example

sprintf('%02.2f', 1); yields at least the decimal seperator "." plus at least 2 characters for the precision. Since that is already 3 characters in total, the %02 in the beginning has no effect. To get the desired "2 leading zeros" one needs to add the 3 characters for precision and decimal seperator, making it sprintf('%05.2f', 1);

sprintf('%02.2f',1);产生至少十进制分隔符“。”加上至少2个字符的精度。由于总共已有3个字符,因此开头的%02无效。要获得所需的“2前导零”,需要为精度和小数分隔符添加3个字符,使其成为sprintf('%05.2f',1);

Some code

$num = 42.0815;

function printFloatWithLeadingZeros($num, $precision = 2, $leadingZeros = 0){
    $decimalSeperator = ".";
    $adjustedLeadingZeros = $leadingZeros + mb_strlen($decimalSeperator) + $precision;
    $pattern = "%0{$adjustedLeadingZeros}{$decimalSeperator}{$precision}f";
    return sprintf($pattern,$num);
}

for($i = 0; $i <= 6; $i++){
    echo "$i max. leading zeros on $num = ".printFloatWithLeadingZeros($num,2,$i)."\n";
}

Output

0 max. leading zeros on 42.0815 = 42.08
1 max. leading zeros on 42.0815 = 42.08
2 max. leading zeros on 42.0815 = 42.08
3 max. leading zeros on 42.0815 = 042.08
4 max. leading zeros on 42.0815 = 0042.08
5 max. leading zeros on 42.0815 = 00042.08
6 max. leading zeros on 42.0815 = 000042.08

更多相关文章

  1. PHP中出现BOM字符\ufeff,PHP去掉诡异的BOM \ufeff
  2. 从JSON字符串/数组中提取第一个图像
  3. 测试一个字符串是否包含PHP中的单词?
  4. 几个有用的php字符串过滤,转换函数代码
  5. PHP - 将字符串转换为键值数组
  6. 使用mod_rewrite将文件夹转换为查询字符串
  7. 计算字符串的MD5哈希值
  8. 有一种防弹的方法可以检测php字符串中的base64编码吗?
  9. PHP替换标签字符

随机推荐

  1. PHP中__set()方法详解
  2. PHP中__invoke()方法详解
  3. 编译安装 ProtoBuf 扩展
  4. PHP 数据加密的方法
  5. TP5.0 PHPExcel 数据表格导出导入
  6. PHP识别相片是否是颠倒的,并且重新摆正相
  7. 避坑!用 Docker 搞定 PHP 开发环境搭建
  8. php开发常见问题总结
  9. PHP中的进制转换
  10. PHP中关于trait使用方法的详细介绍