I am using number_format
to display decimal numbers in different formats (prices, according to regional config, etc.). I prefer it to money_format
. In any case, the number_format is used to display a text quantity, so, for example, I will display $1,203.56
for US and 1.090,00€
for Europe. Of course, the internal calculation of sum of prices of items, etc., I use number_format
to round prices, discounts, etc. And I use
number_format($price * quantity- $discounts ... , 2, ".", "");
I understand that this is correct and will add all values perfectly, and limited to 2 decimal points in the final result. I store this in the database, and later, in navigator screen, shows the number_format
version for each case (text). But I am worried that in my server, they could change configuration and suddenly PHP would use ,
as decimal separator, mixing the calculated quantities? Is that possible or it is warranty that always the scientific notation of .
as decimal points and no thousand separator will be used in calculation of numbers? I am worried because PHP is not typed, so the "type" of number_format
is string. Must I also cast to (float)
? The tests I have done are OK but I am worried that something may gone wrong.
You’re right to be worried, which is why you should store numbers in storage in their raw, numeric format, and not as a formatted string. Calculations should be performed on numeric values, and not values gained from reverse-engineering string representations.
So, store the number in a DECIMAL
(or, even better, store the value in cents in an INT
column), and then format the number in your view.
<?php echo '$'.number_format($price); ?>