1

I am returning JSON from this array, but the value of total is in string format - not a float. Not sure what I am doing wrong here.

This is the array, which ends up having a string:

return [ 
    'cart' => [
        'total'  => amount($cart->total)
    ]
]

And this is the amount helper method, where the issue is coming from:

function amount($money)
{
    return number_format(floatval($money), 2);
}

I am expecting a float back from total, not a string.

zbee
  • 959
  • 1
  • 7
  • 29
burtonLowel
  • 734
  • 7
  • 17
  • If you question has been answered, accepting an answer with the check mark can help others find an answer in the future and aid the rest of the community in focusing efforts. – zbee Oct 25 '19 at 19:48

2 Answers2

5

number_format returns a string.

In your case, you might be passing a value such as 3.15 in which case a string would seem to be an odd output. But, if you passed a value like 311583249 you would see why this is the case: number_format(311583249) returns "311,583,249".

It returns a string every time for continuity. If it returned an integer when there's a whole number less than 1,000, or a a float when there's a partial number less than 1,000, then that would be more difficult to account for overall and not serve the exact purpose that number_format has - so a string is always returned by number_format.

What you might be looking for instead would be round(X, 2); this would return a float with the precision of 2. Or maybe you're looking for money_format('%i', X) - this also returns a string but formatted as if it were money.

zbee
  • 959
  • 1
  • 7
  • 29
-1

That's normal. In this case, if you break down the types of everything you're executing like so:

var_dump(1000000.12);
var_dump(floatval(1000000.12));
var_dump(number_format(floatval(1000000.12), 2));

Then you will notice that number_format is the point at which it becomes a string, given the comma delimitation:

float(1000000.12)
float(1000000.12)
string(12) "1,000,000.12"

Also this may be useful for you as an alternative approach.

zbee
  • 959
  • 1
  • 7
  • 29
boolfalse
  • 1,892
  • 2
  • 13
  • 14
  • thank you both! However, this still happens for numbers less than 999 (no comma). It would be returned as "999" – burtonLowel Oct 24 '19 at 21:28
  • @burtonLowel That is correct, it only returns strings. It doesn't make a lot of sense other than continuity for whole numbers under 1,000, but that is why. – zbee Oct 24 '19 at 22:02