1

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 :)

2
  • 2
    number_format() returns a string with comma-grouped thousands by default. Commented Nov 16, 2018 at 15:28
  • And what exactly do you mean by "with floatval() and It didn't run either."? What did happen? Seems to me that it would produce a valid result, so you need to be clear about in what way it wasn't what you wanted. Commented Nov 16, 2018 at 15:35

2 Answers 2

1

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.

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.