"1,234" to 1234
Moderator: General Moderators
"1,234" to 1234
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.
Thanks for reading.
Re: "1,234" to 1234
Have you tried number_format()?
Re: "1,234" to 1234
I've tried:
but it doesn't work. Though I've tried:
and that seems to work.
Let me know if you find anything easier.
Code: Select all
number_format($_POST['price'], 2, ".", "");Code: Select all
floor(str_replace(",", "", $_POST['price'])*100)*.01Let me know if you find anything easier.
Re: "1,234" to 1234
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
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
Ah ok, I would use preg_replace then and your customized floor statement.
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Re: "1,234" to 1234
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.
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.