带有前导零的正浮点数和负浮点数的 PHP 格式


PHP formatting of positive and negative floating point numbers with leading zeros

场景:
修剪正浮点数和负浮点数的前导零

输入:

000.123
00.123
01.123
-001.123
-00.123
-040.123

期望输出:

0.123
0.123
1.123
-1.123
-0.123
-40.123

问题:
是否有一个内置函数可以使这种特定的格式比通过substr()strpos()explode()if语句的组合来运行每个数字更容易和更有效?

我想你的数字被保存为一个字符串,所以为了得到你的输出,你只需简单地将它们投射到一个floatdouble,如下所示:

echo (float) $number;

有关铸造的更多信息,请参阅手册:http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting

只需将其转换为float

像这个例子:

<?php
$number = '-000.220';
echo (float)$number;

这样,您可以删除所有前导零,无论是正数还是负数