Page 1 of 1

"1,234" to 1234

Posted: Tue Mar 10, 2009 11:46 pm
by JellyFish
I've been googling for quite a while now and I can't seem to find a php solution that will convert a string "1,234" to a number 1234. I'd think there would be more on this seeing as how someone could easily place commas in a number field of an HTML form. What's the most simple way to remove the commas in a string and convert it into a number (float or integer)?

Thanks for reading.

Re: "1,234" to 1234

Posted: Tue Mar 10, 2009 11:47 pm
by Benjamin
Have you tried number_format()?

Re: "1,234" to 1234

Posted: Wed Mar 11, 2009 12:02 am
by JellyFish
I've tried:

Code: Select all

number_format($_POST['price'], 2, ".", "");
but it doesn't work. Though I've tried:

Code: Select all

floor(str_replace(",", "", $_POST['price'])*100)*.01
and that seems to work.

Let me know if you find anything easier.

Re: "1,234" to 1234

Posted: Wed Mar 11, 2009 12:14 am
by Benjamin
If you are expecting an integer and they post a float I would throw an error message, but this is probably how I would do it.

Code: Select all

 
echo floor(preg_replace('#[^\d\.]#', '', '1,234,567,890.23'));
 

Re: "1,234" to 1234

Posted: Wed Mar 11, 2009 12:31 am
by JellyFish
Actually I'm expecting either a float or an integer. The floor function actually floors everything below the hundredths place. I multiply by 100 then after the floor divide by 100 (or multiple by .01, which is mathimaticaly the same thing). :)

Re: "1,234" to 1234

Posted: Wed Mar 11, 2009 12:58 am
by Benjamin
Ah ok, I would use preg_replace then and your customized floor statement.

Re: "1,234" to 1234

Posted: Wed Mar 11, 2009 1:42 am
by Chris Corbyn
It's dangerous to remove commas from numbers based on the assumption that they're meaningless ;) I've been bitten by making this assumption.

Basically, if a user sends you this:

50,00

You'd strip it to

5000

Now, is that correct? Maybe, if you're American or English? Probably not if you're European.

It's very locale-specific how you treat the comma. Like astions says, produce a validation error, don't auto-fix what you may be breaking.

Re: "1,234" to 1234

Posted: Thu Mar 12, 2009 4:18 am
by Weirdan