4

I have this code to give $value a number format:

    $value=1000000.00;

    number_format($value,2);

    echo str_replace(",", "", $value)

But when I try to replace the comma, the decimals get removed. I want to print $value as it originally was: 1000000.00. How can I do that?

Errol Chaves Moya
  • 307
  • 2
  • 5
  • 20
  • you can tell [number_format](http://php.net/manual/en/function.number-format.php) what it should use as decimal-seperator! No need for the str_replace – Jeff Mar 14 '19 at 22:49
  • Duplicate: https://stackoverflow.com/questions/4483540/show-a-number-to-2-decimal-places/4483561#4483561 (cannot vote due to retracted previous vote) – Pinke Helga Mar 14 '19 at 22:53
  • @Quasimodo'sclone yes and no. the real issue here was the failure to assign the output of `number_format`. – Nick Mar 14 '19 at 22:56
  • @Nick the question is how to properly achieve the intended result, the duplicate actually answers this. – Pinke Helga Mar 14 '19 at 22:58
  • 1
    @Quasimodo'sclone fair enough. done. – Nick Mar 14 '19 at 23:07

2 Answers2

8

You have to assign the output of number_format to the variable:

$value=1000000.00;
$value = number_format($value,2);
echo str_replace(",", "", $value);

Output:

1000000.00

You can also simply tell number_format not to use a thousands separator:

$value = number_format($value,2,'.','');
echo $value;

Output:

1000000.00

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
4

You can tell number_format what it should use as decimal-point and thousands-seperator! No need for the str_replace:

$value = 1000000.00;
echo number_format($value, 2, ".", "");
// output:
// 1000000.00
Jeff
  • 6,895
  • 1
  • 15
  • 33