php - 添加逗号千位分隔符但删除尾随零

时间:2014-12-15 15:23:09

标签: php

我正在尝试使用PHP将数字格式化为

  1. 删除所有尾随零

  2. 为千位分隔符添加逗号

  3. 列出两个小数点,假设它们不是零

  4. 我试过这个,但它并没有完全按照我的目标去做:

    $prices[$title]['reg_price'] = (float)number_format($membership->sell_price, 2, ".", "");
    $prices[$title]['three_year_price'] = (float)number_format($membership->attributes[$aid]->options[$three_year_oid]->price, 2, ".", "");
    

    我发现我可以通过将数字转换为浮点来删除尾随零。但是,我发现我需要告诉number_format不要使用千位逗号分隔符,否则,当将1,500.00转换为浮点数时,结果为1.

    因此,总而言之,我希望我的代码更改1500.00到1,500,150.00到150和19.99到19.99。我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:6)

function parseCurrency($value) {
    if ( intval($value) == $value ) {
        $return = number_format($value, 0, ".", ",");
    }
    else {
        $return = number_format($value, 2, ".", ",");
        /*
        If you don't want to remove trailing zeros from decimals,
        eg. 19.90 to become: 19.9, remove the next line
        */
        $return = rtrim($return, 0);
    }

    return $return;
}

$prices[] = parseCurrency(1500.00);
$prices[] = parseCurrency(1500.10);
$prices[] = parseCurrency(1500.1);
$prices[] = parseCurrency(1500);
$prices[] = parseCurrency(123.53);
$prices[] = parseCurrency(1224323.53);
$prices[] = parseCurrency(19.99);

print_r($prices);

输出:

Array
(
    [0] => 1,500
    [1] => 1,500.1
    [2] => 1,500.1
    [3] => 1,500
    [4] => 123.53
    [5] => 1,224,323.53
    [6] => 19.99
)

答案 1 :(得分:1)

这将插入逗号,四舍五入到小数点后两位小数,删除尾随零,并删除尾随“。”:

rtrim(rtrim(number_format($value,2),0),'.')

答案 2 :(得分:-1)

您可以使用

ltrim($var, '0'); 

删除前导0。并且

rtirm($var, '0');

到尾随。

答案 3 :(得分:-1)

替换“。” “,”你可以使用一个函数:

function replace_dot($value) {
    $str = str_replace('.', ',', $value);
    return $str;
}
相关问题