0

I'm trying to convert a currency string to a number. I'm using a replace function with a regexp that I've used successfully in a similar context before.

The currency string is captured here, in part of an "each" loop:

var unitGridPrice = jQuery(this).find(".clsPriceGridDtlPrice").html();

The result is that unitGridPrice is a currency string, something like "$2.75". I'm trying to convert it to a number here:

var priceToConvert = unitGridPrice;
var unitGridPriceNo = Number(priceToConvert.replace(/[^0-9\.]+/g, ''));

However with that last line in place, the script will not run.

If I use the value of priceToConvert it correctly displays the currency text string, so I believe the string feeding the replace function is correct.

if I change "var priceToConvert = unitGridPrice" to "var priceToConvert = "$2.75" the script properly returns 2.75. I can copy and past the value that unitGridPrice displays into the text string I'm testing with and it works, but with the variable there the script dies.

I've tried removing the regex, changing the replace to .replace('$', '') and again the script stops with the variable in place but works if I test with a fixed string.

I'm really stumped. Help??!! Thank you!!!

  • What do you mean the script dies? Do you get any errors? – univerio Jun 17 '14 at 1:10
  • What does console.log(unitGridPrice) show you? – Jason P Jun 17 '14 at 1:22
  • The script does not complete and I get the error "priceToConvert is null" I tried forcing the output of the jQuery call using the "String" function (grasping at straws) and the error message changed to "String is not defined". In the same code if I remove the replace function and assign unitGridPrice to the variable "priceToConvert" I get exactly the string I am trying to convert. Baffling. I need to sleep on this. – dexter Jun 17 '14 at 3:33
  • I tried again adding the "String" function to verify the error message but now the code is working as expected. WooHoo! (I think) I'm closing it down for the night and trying to see what is going on tomorrow. Hopefully it remains functional while I finish this small project. Thank you for the help, any other insight at what might be going on is appreciated. – dexter Jun 17 '14 at 3:45
0

i had some problem while try to get number from string also, little time ago. the problem is the regex, so i changed the regex like code below.

var id = element.name.replace ( /[^\d.]/g, '' );

element.name above is like input_21,input_22, etc. and i wanna get only the number(21,22). hope it can help you. :)

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.