printf&&sprintf

<?php
$num = 5;
$location = 'tree';

$format = 'The %2$s contains %1$d monkeys';
echo sprintf($format, $num, $location);
?>

The tree contains 5 monkeys

$format = 'The %2$s contains %1$04d monkeys';
echo sprintf($format, $num, $location);

The tree contains 0005 monkeys

$pattern = '%1$s %1$\'#10s %1$s!';

printf($pattern, "badgers"); 
echo "<br>";

printf("[%10.10s]\n", "badgers");
echo "<br>";
echo sprintf("%'.9d\n", 123);
echo sprintf("%'.09d\n", 123);

 

badgers ###badgers badgers!
[ badgers] 
......123 000000123

$number = 123;
printf("有两位小数:%1\$.2f<br>没有小数:%1\$u",$number);

如果 % 符号多于 arg 参数,则您必须使用占位符。占位符位于 % 符号之后,由数字和 "\$" 组成。、

 

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

Yields 1.00. 

This threw me a little off. To get the desired result, one needs to add the precision (2) and the length of the decimal seperator "." (1). So the correct pattern would be

<?php
sprintf('%05.2f', 1);

 

05,0在前面表示后面的数字表示长度

 

posted on 2016-01-04 16:05  阿卡贝拉  阅读(191)  评论(0)    收藏  举报