clean currency input

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
Hi Folk

I wrote the following function as a "cleaner" for a currency input:

function is_currency($v) {
//returns a string with only the numbers for a currency format
 $v = str_replace("$", "", $v);
 $regex = '/(?:([0-9]+)|.)/';
 if(preg_match($regex, trim($v) ) ){
  $v = $v + 0.00001;
  if (is_float($v)) {
   return round($v, 2);
 else {
  return 0;

I want users to be able to put in things like:
and it should always translate into a number with two decimals (e.g. 12.34  
or 12.00)

I am sure that this is probably the clumsiest way ever to do this.  How can  
I improve this function?


PS despite numerous efforts I am still super weak on regular expressions.  I  
can only copy them and not write them myself.  

Re: clean currency input

Hello Nicolaas,

Take a look at my code for this action, i think it's more accurate:

function is_currency( $v )
      $v = preg_replace("/[^0-9.]+/","",$v);
      return round($v,2);

Quoted text here. Click to load it

Re: clean currency input

windandwaves wrote:
Quoted text here. Click to load it

function format_currency($n) {
    $n = preg_replace('/[^\d.]+/', '', $n);
    return sprintf('%01.2f', $n);

As you will notice, I have also modified the function name as "is_currency"  
suggests that it returns a boolean rather then a formatted number.

For currency formatting you can apply the number_format() function, in case  
you've missed it.


Re: clean currency input

windandwaves wrote:

Thanks guys -

That is awesome.


Site Timeline