danny2327
danny2327

Reputation: 97

Twig 2 - Incorrect value from 2 number_format

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:

  1. This only occurs if the price is over $1000, otherwise it's fine. This doesn't happen if the price is under $1000 but when multiplying the quantity, the total is over $1000 - I feel like this can't be a coincidence. Something to do with the number of digits maybe?
  2. I have it in a variable as a test, I had originally had it in line but also I get the error message: "$ Notice: A non well formed numeric value encountered in C:\Apache24\htdocs\tekinventory.dev\vendor\twig\twig\lib\Twig\Environment.php(372) : eval()'d code on line 198 2.00 "
    as well as the value 2.00
  3. If I take the "|number_format(2)" off of the set price line, everything works fine, except that I then occasionally get rounding errors in the final price (the original problem)

I've also read the

Is this a known bug, or am I doing something wrong? Thanks

Upvotes: 1

Views: 1109

Answers (1)

JBH
JBH

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

Related Questions