我想知道是否存在一些函数来自动格式化一个数字的小数,所以如果我有:
<?php
// $sql_result["col_number"] == 1,455.75
number_format ($sql_result["col_number"], 2, ".", "");
// will return 1455.75
// $sql_result["col_number"] == 1,455.00
number_format ($sql_result["col_number"], 2, ".", "");
// could I get 1455 instead of 1455.00?
?>
所以我的答案是,如果我的DB中只有DECIMAL数据格式,那么如果确实存在一些删除小数的方法吗?
或者我应该做那样的事情?
<?php
// $sql_result["col_number"] == 1,455.00
str_replace(".00", "", (string)number_format ($sql_result["col_number"], 2, ".", ""));
// will return 1455
?>
我实际上认为你的解决方法和任何方法一样好。它简单明了,在这里谈论性能真的没有意义,所以就去吧。
我被指责做这样的事情:
floatval($foo) == intval($foo) ? number_format($foo) : number_format($foo,2);
关于什么
number_format($value,2) - 0;
floatval或简单地转换为浮动
php > echo floatval(7.00);
7
php > echo floatval(2.30);
2.3
php > echo floatval(1.25);
1.25
php > echo floatval(1.125);
1.125
php > echo (float) 7.00;
7
php > echo (float) 2.30;
2.3
php > echo (float) 1.25;
1.25
php > echo (float) 1.125;
1.125
正如埃米尔说你的好。但是如果你想从中删除0
7.50
,我有一个建议,rtrim()
:
<?php
// if $sql_result["col_number"] == 1,455.50
rtrim(rtrim(number_format($sql_result["col_number"], 2, ".", ""), '0'), '.');
// will return 1455.5
?>
我添加文章Remove useless zero digits from decimals in PHP作为一种更好的方法来清除值,如果需要,没有宽松小数。
您也可以使用rtrim(),这将删除多余的0,在您可能想要保留一个小数位但不是多余的零的情况下。 (例如,4.50变为4.5。)还允许您将小数位数从2更改为任何其他数字。
rtrim(rtrim((string)number_format($value, 2, ".", ""),"0"),".");
// 4.00 -> 4
// 4.50 -> 4.5
// 4.54000000 -> 4.54 (if you're doing more decimal places)
实际上我觉得我能想到的最干净的方法是为那些刚刚进行搜索寻找此类事情的人做这件事:
( number_format ($sql_result["col_number"], 2) * 100 ) / 100;
如果您要定位美国货币,我想使用此方法:
function moneyform($number, $symbol = true) {
return str_replace(".00", "", money_format(($symbol? '%.2n' : "%!n"), $number));
}
moneyform(1300999);
-->$1,300,999
moneyform(2500.99);
-->$2,500.99
moneyform(2500.99, false);
-->2,500.99
沃伦。答案帮助了我。我不需要number_format函数,所以我就这样做了
$value=$value-0;
但在OP的情况下,他需要number_format来删除逗号。所以这对他有用
$value=number_format ($sql_result["col_number"], 2, ".", "")-0;
由于我找不到灵活的解决方案,我编写了一个简单的函数来获得最佳结果:
function getValueFormattedWithMinimalDecimals($value, $max_decimals = 2, $dec_point = ',', $thousands_sep = '') {
$bestNumberOfDecimals = -1;
$decimal = 0;
while ($decimal <= $max_decimals) {
$bestNumberOfDecimals = $decimal;
$valueDecimals = number_format($value, $decimal);
if (floatval($value) == $valueDecimals) {
break;
}
$decimal++;
}
if($bestNumberOfDecimals > 0 && number_format($value, $bestNumberOfDecimals) == number_format($value, 0)) {
$bestNumberOfDecimals = 0;
}
return number_format($value, $bestNumberOfDecimals, $dec_point, $thousands_sep);
}