method giving price as a string, and not a float - php

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.

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.

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.

Related

PHP Float conversion fails, returns 1

I have a function which returns a value of 1725.00 using the number_format(value,2). So, now when I convert it to float, it gives 1, same for int,intValue,floatValue. Even I tried multiplying with 100 to get the int value, but it gives an error of A non well formed numerical value. Does anyone know what is wrong here?
$balance = (float) currentBalance($user_id); // currentBalance gives a value of 1725, but (float) gives makes the value 1.
print_r($balance); die; //gives 1.
I'm using PHP 7.0+ and Laravel 5.8.
Your problem is that number_format returns a string with commas inserted for thousand separators, so the return value from your function is 1,725.00. When you try to cast this as a float PHP gets as far as the comma and says this is no longer a number and so returns 1.
If you need to have a formatted string returned by currentBalance, your best bet is to use
$balance = (float)str_replace(',', '', currentBalance($user_id));
Otherwise, replace the call to number_format with a call to round so that currentBalance returns a numeric value instead.

Safely round numbers in php using strings to avoid evil float

I use bcmath for my calculations and I want to round some numbers to n decimal places. Now, I know enough to avoid floats, but what I'm wondering is if the following example is safe and/or if there are better ways to do it?
$number = '123.456'; // number to round as string
$roundedNumber = (string) round($number, 2); // round and cast
// calculations using bcmath continue here...
I think it is, I've ran some experiments and so far it always returned expected result but I'd like second opinion as I'm not 100% positive that in some particular case casting string to float and then float back to string will not output undesired result.
Or is there a better way to do this?
EDIT: before you answer:
bc* functions do not round when third parameter is specified, they just trim the output.
number_format does not allow selection of rounding mode, so it's out
EDIT: What do I consider safe?
Given the number as string and rounding mode, will the function always output correct/expected result and not be affected by casting to float?
I guess that what I'm being afraid of is following:
I provide number say 12.345 as string to round function, it gets casted as float and then my number isn't 12.345 anymore, it may be 12.345xxxx because we all know how float can be represented internally. I'm afraid of that affecting the rounding output. I believe there will be no harm when I cast to 12.345 to string, it will always be '12.345', not '12.345....' right?

numberformat error with bigs numbers in php

I'm developing a e-commerce and I have a problem when I want to format a number with number_format().
I have to set to my Stripe connection a number without decimals, so when I do all the calculations to have the final price of my shoppingcart I do:
$final_amount = number_format($final_amount, 2) * 100;
The result is a number that Stripe understands. I haven't got any problem with small numbers (like 970.25 or 1300.75 for example) but when I have a big amount like 15717.72 php throws the error "A non well formed numeric value encountered". I don't know if this is the problem, big numbers.
I've tried to parse previously $final_amount with floatval() and It didn't run either.
Someone knows the problem? thanks :)
A couple notes.
"A non well formed numeric value encountered" is a Notice, not an Error.
I don't believe 1300.75 works for you. The reason I don't believe this is you are only giving number_format two parameters. You are receiving that notice because number_format is formatting your number with a thousands separator ",".
$final_amount = number_format($final_amount, 2, ".", "") * 100;
should do the trick to remove that notice.
problem is not number_format() function but your calculation. You are multiplying a string with an integer. That does not work out so well.
$final_amount = number_format($final_amount * 100, 2);
Works just fine.
Update:
My conclusion was not completely correct. Multiplying an int with an string does work if the string is castable to int or float (see type juggling in PHP manual). But the string created by number_format() looks like this: "15,717.72". And thus cannot be cast to a number type.

Need to cast string value representing a 0.XXXX floats to actual number value in PHP

So I am trying to cast a string value of ie: '0.0000143' to actual FLOAT or DECIMAL number value (so it must not be a string after conversion), but the actual number of 0.0000143 as it needs to be sent through some API call and the API requires it to be structured like that and not have an actual string value.
Can anyone help me achieve this (or is it actually even possible to do)?. Since I am out of ideas
To make things more clear, I have tried all the type casting possibilities there are in PHP (it is not working as I do not need something like 1.4E-5 returned to me, but the actual value like 0.0000143).
You can use Type casting in order to achieve that:
$string = '0.0000143';
$intValue = (int)$string;
$floatValue = (float)$string;

PHP string to numeric conversion with decimal places

I have a string ($maxDeposit) which is a numeric monetary value. So, for example:
123.00
This string is being passed in to jQuery, it needs to be passed in as a numeric data type. I'm achieving this using the following:
$maxDeposit = floatval($maxDeposit);
This loses the last last decimal place however, so my number looks like:
123.0
I have this method of converting the number to two decimal places:
$maxDeposit = sprintf('%0.2f', round($maxDeposit, 2));
However this also converts the number back to a string. Is there a way I can convert the string to a float but keep the last decimal place? Thanks
No, float is a numeric value, and 123.00 is its representation with 2 decimal places. It is responsibility of view layer to format numbers. In your case it is jQuery, e.g. console.log(maxDeposit.toFixed(2)).
I think, You can use floatval/float and number_format.
$maxDeposit = number_format(floatval($maxDeposit), 2);
or
number_format((float)$maxDeposit, 2, '.', '');
http://php.net/manual/pt_BR/function.number-format.php

Categories