unemployment Posted April 30, 2011 Share Posted April 30, 2011 When I post the data to mysql I want to submit the value as an integer. How can I make this $12,000 be 12000? Quote Link to comment https://forums.phpfreaks.com/topic/235150-make-currency-an-integer/ Share on other sites More sharing options...
fugix Posted April 30, 2011 Share Posted April 30, 2011 I would use preg_replace() Quote Link to comment https://forums.phpfreaks.com/topic/235150-make-currency-an-integer/#findComment-1208508 Share on other sites More sharing options...
Fadion Posted April 30, 2011 Share Posted April 30, 2011 There may probably a better and faster way than regex, but this came in mind right now: <?php $money = '$12,000'; //replace every character except numbers (0-9) $s = preg_replace('|[^0-9]|i', '', $money); //int cast a new variable $n = (int) $s; var_dump($s); //string(5) "12000" var_dump($n); //int(12000) ?> Just for the sake of clarity, I've posted some lines where you can actually see what type the variable is. Just running a preg_replace() would make it look like an integer, but the data type would be a string. By int casting it, you can really convert it to an integer data type. Summing it up, you can write both the regex and int cast in one line: <?php $s = (int) preg_replace('|[^0-9]|i', '', $money); var_dump($s); //int(12000) ?> Just keep in mind that when talking about money, most surely you'll have decimal points, unless you're dealing with big, fixed amounts. In that case, integers won't do it and you'll need floats. Quote Link to comment https://forums.phpfreaks.com/topic/235150-make-currency-an-integer/#findComment-1208510 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.