tags:

views:

1235

answers:

4

I have a javascript function that accepts a number and performs a mathematical operation on the number. However, the number I'm passing in could have a comma in it, and from my limited experience with Javascript I am having problems working with that value. It doesn't seem to treat that as a numeric type.

What's the easiest was to take a parameter with a value of 1,000 and convert it to a numeric 1000?

+2  A: 

Just replace all the commas with a blank.

You can follow this: http://blog.techsaints.com/2007/06/25/javascript-how-to-remove-all-commas-from-a-number/

James Black
I found that article earlier, but I was confused as to where the FormValue item came from.
Mike C.
with an empty string ("a blank" might be construed as "a space")
Anonymous
FormNumber should be StartNumber in the link I had mentioned, it appears.
James Black
+5  A: 

You can set up your textbox to have an onblur() function so when the user attempts to leave the textbox, you then remove the commas from the value by using the javascript replace function

example:

  function checkNumeric(objName)
  {
    var lstLetters = objName;

    var lstReplace = lstLetters.replace(/\,/g,'');
  }  

With input tag here:

<input type="text" onblur="checkNumeric(this);" name="nocomma" size="10" maxlength="10"/>
TStamper
The javascript function I'm talking about is already hooked up to the onblur event. I was specifically looking for javascript code to remove the comma from the value.
Mike C.
updated with answer
TStamper
I'll give this a try. It looks like the replace method was what I was looking for.
Mike C.
+3  A: 

A quick and dirty way is to use the String.replace() method:

var rawstring = '1,200,000';
var cleanstring = rawstring.replace(/[^\d\.\-\ ]/g, '');

This will set cleanstring to: 1200000. Assuming you are using US formatting, then the following conversions will occur:

1234 --> 1234
1,234 --> 1234
-1234 --> -1234
-1,234 --> -1234
1234.5 --> 1234.5
1,234.5 --> 1234.5
-1,234.5 --> -1234.5
1xxx234 --> 1234

If you are in other locales that invert the '.' and ',', then you'll have to make that change in the regex.

johnvey
A: 

I have a javascript function that accepts a number and performs a mathematical operation on the number.

Let me know if the function below ever produces output that is not a valid Number.

Note: the 2nd parameter is purely optional, and it is to specify the number of allowed decimal places (if needed); it defaults to 2 decimal places.

function unComma( val, dec )
{    
    var newVal  = 0, 
     defaultVal = 0,  
     dec  = (dec || 2);

    if ( !val )
     return defaultVal;

    val = val.toString().replace(/,/g, '');

    if ( !val )
     return defaultVal;

    newVal = parseFloat(val);

    if ( isNaN(newVal) )
     return defaultVal;

    newVal = +( newVal.toFixed(dec) );

    return ( newVal || defaultVal );
}
ken