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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.