'php - add comma thousands separator but remove trailing zeros

I am trying to use PHP to format a number to

  1. Remove all trailing zeros

  2. Add a comma for the thousands separator

  3. List two decimal points, assuming that they are not zeros

I tried this, but its not doing exactly what I am trying to achieve:

$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, ".", "");

I had found that I could strip trailing zeros by casting the number to a float. However, I found that I needed to tell number_format NOT to use the thousands comma separator, because otherwise, when casting 1,500.00 to a float, the result was 1.

So, in summary, I want my code to change 1500.00 to 1,500, 150.00 to 150, and 19.99 to 19.99. How can I make this happen?

php


Solution 1:[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);

Outputs:

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
)

Solution 2:[2]

This inserts commas, rounds to 2 decimal places, removes trailing zeroes, and removes trailing '.':

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

Solution 3:[3]

You can use the

ltrim($var, '0'); 

to remove the leading 0. And

rtrim($var, '0');

to remove the trailing.

Solution 4:[4]

For replacing "." to "," u can use a function :

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Keith Turkowski
Solution 3 Redox
Solution 4 Alex