How to strip dollar signs and/or commas?

5 posts by 2 authors in: Forums > CMS Builder
Last Post: November 2, 2012   (RSS)

By furcat - October 25, 2012

Are there any functions for stripping off commas or dollar signs from numbers? I need to use numbers entered by my customer in calculations, and don't want the commas.

But, for display purposes, the dollar sign and commas makes reading the numbers on the web page a lot easier.

Any help or advice is welcome!

Thanks.

Re: [furcat] How to strip dollar signs and/or commas?

Hi,

If you want to strip the dollar sign and comma from a number you could use these functions together:

$value = preg_replace('/[\$,]/', '', $value);
$value = floatval($value);


The preg_replace function will strip out the dollar sign and any commas. The floatval function will convert the number from a string to a floating value, ensuring it will behave like a number if you want to use it for addition, multiplication, etc.

To convert the number back to a currency format I would use this:

echo '$ '.number_format($number, 2, '.', ',');

The number_format function will take a number and convert it into string format it. In this case it makes the number have two decimal places and adds a comma for every 3 digits.

Thanks!
Greg Thomas







PHP Programmer - interactivetools.com

Re: [greg] How to strip dollar signs and/or commas?

By furcat - October 26, 2012

Thank you very much. That is what I needed.

I also need a little more info, though.

When creating a search using numeric values, such as what I have shown below, how do I force the search to strip any dollar signs or commas that was placed in the field "purchase_price"?

<select name="purchase_price_min">
<option value="0">&lt;minimum&gt;</option>
<option value="0">$0</option>
<option value="500000">$500,000</option>
<option value="1000000">$1,000,000</option>
</select>
&nbsp;
<select name="purchase_price_max">
<option value="">&lt;maximum&gt;</option>
<option value="500000">$500,000</option>
<option value="1000000">$1,000,000</option>
<option value="">&gt;$1,000,000</option>
</select>

Thank you.

Re: [greg] How to strip dollar signs and/or commas?

By furcat - November 2, 2012

Thanks guys. I think I'm going to restrict data entry to numbers only, and then put the correct format for dollar amounts when I display the data.