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

use*_*214 0 php

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

  1. 删除所有尾随零

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

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

我试过这个,但它没有完全按照我要做的去做:

$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, ".", "");
Run Code Online (Sandbox Code Playgroud)

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

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

Kir*_*rbo 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);
Run Code Online (Sandbox Code Playgroud)

输出:

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
)
Run Code Online (Sandbox Code Playgroud)