0

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.

1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I used round as well and it gives 1.
@Rob13 you changed the call to number_format inside currentBalance to round? That should have worked. If it didn't, I'd need to see the code for currentBalance to understand why. Regardless, the use of str_replace I have suggested in the answer will work.
Yeah, sorry it worked, I understood something different previously. So, I read your comment again and understood this time. Your answer makes perfect sense. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.