PHP:如何添加前导零/零填充以通过sprintf()进行浮动? [英] PHP: How to add leading zeros/zero padding to float via sprintf()?

查看:147
本文介绍了PHP:如何添加前导零/零填充以通过sprintf()进行浮动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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('%02d', 1);

这将导致01.但是,对具有精度的浮点数尝试相同的方法无效:

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

sprintf('%02.2f', 1);

收益率1.00.

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

How can I add leading zeros to a float value?

推荐答案

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

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

请注意,如何用%05替换%02.

说明

论坛帖子在正确的方向:第一个数字既不表示前导零,也不表示小数点分隔符左侧的总字符数,但不表示结果字符串中的字符总数!

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!

示例

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

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

某些代码

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

输出

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

这篇关于PHP:如何添加前导零/零填充以通过sprintf()进行浮动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆