php - add comma thousands separator but remove trailing zeros



PHP Snippet 1:

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

PHP Snippet 2:

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
)

PHP Snippet 3:

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

PHP Snippet 4:

ltrim($var, '0'); 

PHP Snippet 5:

rtrim($var, '0');

PHP Snippet 6:

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