Reputation: 97
I'm seeing some odd behaviour from twig 2 trying to use number_format.
I get 3 values from my server for each item: cost, multiplier and quantity. Because of the multiplier I was getting partial cents when multiplying by the quantity, so I put price in a variable like so:
{% set price = (item.buyPrice * item.markup_mult)|number_format(2) %}
That's fine, I use it on the next line and it's correct. The problem is when I try to use the price value in another variable with a second formatting:
{% set lineTotal = (price * quantities[item.collection_id][item.item_id])|number_format(2) %}
Like this, I will get the value of 2.00, because my lineTotal SHOULD have been 2400 something.
3 Things to note:
I've also read the
Is this a known bug, or am I doing something wrong? Thanks
Upvotes: 1
Views: 1109
Reputation: 1958
number_format
outputs a string, meaning you're trusting automatic type conversions. When you use number_format
by default it automatically inserts a thousands-delimiter (in the U.S., a comma). That's probably messing up your math and explains why it's only a problem for prices above $999.99.
Rather than using number_format
, you need to use round()
.
$number = 1000.999
echo number_format($number,2); // 1,001.00
echo round($number,2); // 1001
$number = 1000.99
echo number_format($number,2); // 1,000.99
echo round($number,2); // 1000.99
Upvotes: 2