Peter Lur
Peter Lur

Reputation: 758

Number losing its format

Whenever I assign number_format to a number, it lose its format as soon as I add or substract any other numbers to it.

How can I set a number variable only once to make sure it always keep it's decimal state?

I don't want to use number_format everytime I add or substract any other numbers to it. I want to set it once.

$array = array(
    'a'=>0,
    'b'=>number_format(0,2)
);

$array['b'] += 5.00;

print_r($array);

//Output: Array ( [a] => 0 [b] => 5 ) 

Upvotes: 0

Views: 130

Answers (2)

raidenace
raidenace

Reputation: 12836

That is the way number_format works. It does not "store" the new format, instead it just returns a formatted string. This string is basically meant for printing purposes.

So when you do

$x = number_format(0,2); echo $x;

It prints 0.00.

Now if you do:

$x = $x+ 5.00; echo $x;

It will print 5 because 5.00 was added to the string 0.00 that results in just 5 because by default these variables are numbers. You again need to do a number_format before printing it:

echo number_format($x,2);

You can test this easily using the code below:

$x = 3.00;
echo $x; //will print 3
echo number_format($x,2); //will print 3.00

Note that this behavior is because the decimal points are zeroes, if they are non-zero values they will be shown correctly.

Upvotes: 2

iggyvolz
iggyvolz

Reputation: 101

number_format() returns a string. You are setting $array['b'] to be "0.00".

When you try to add 5, PHP now converts your string "0.00" to a number, 0, before it adds 5, to become 5.

If you want to make it into the string "5.00", you have to use number_format() every time. However, you can use the following code to force it to run through number_format() automatically:

<?php
class saveNumberFormat
{
  public $val=0;
  public $format=0;
  public function __construct($val,$format)
  {
    $this->val=$val;
    $this->format=$format;
  }
  public function __toString()
  {
    return number_format($this->val,$this->format);
  }
  public function increment($byHowMuch)
  {
    $this->val+=$byHowMuch;
  }
}

Example:

$foo=new saveNumberFormat(5,2);
$foo->val++;
echo $foo; // Returns 6.00

Note that you cannot var_dump() the object, as that would not call __toString().

Upvotes: 0

Related Questions