Jump to content

Make Currency an Integer


unemployment

Recommended Posts

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.