Convert money format to numbers

I have the following tag in html, I donโ€™t want $ to be accepted as just want a price for calculation purposes.

<span id="testspan">$101.82</span> 

in the previous span tag, I want to get only the value 101.82 for calculations.

I use html () to get the value

 var csqft_price = $('#testspan').html(); var price= parseFloat(csqft_price); 

but I get it with $, so I canโ€™t calculate how I can do this.

+4
source share
7 answers

you can use

  var csqft_price = $('#testspan').html(); var number = Number( csqft_price.replace(/[^0-9\.]+/g,"")); 

refer How do I convert a currency string to double using jQuery or Javascript? it is alredy published in SO.

+11
source

The following tests determine if the first character is a dollar sign, and if so, takes the rest of the string:

 var csqft_price = $('#testspan').html(); var price = +(csqft_price.charAt(0)==="$" ? csqft_price.substr(1) : csqft_price); 

Of course, if you know that there will always be a dollar sign, you can simply do this:

 var price = +csqft_price.substr(1); 

Note. I usually prefer the unary plus operator to convert a string to a number, so I used this in my answer above - you can change +(...) to parseFloat(...) if you want.

+3
source

I would replace all non-digets and dots with nothing and do nothing than parseFloat:

 var textValue = '$101.82'; var floatedValue = parseFloat(textValue.replace(/[^\d\.]/, '')); alert(floatedValue); 

Example: http://jsfiddle.net/MEY9R/

+1
source

Try replacing the $ sign with the "replace" javascript function and replace the $ sign with an empty value, for example:

 var vsqft_price = $('#testspan').html(); var vsqft_float = vsqft_price.replace("$", ""); var price= parseFloat(csqft_float); 
0
source

Try it -

  var csqft_price = $('#testspan').text(); var s = csqft_price.substr(1); alert(s); 

http://www.w3schools.com/jsref/jsref_substr.asp

0
source

Use this

 var csqft_price = $('#testspan').html(); var price=parseFloat(csqft_price.replace('$','')); alert(price); 

And use the price to calculate.

0
source

ku4js-kernel has a weak $ .money class for this. You can just $ .money.parse ("$ 101.82") and then do what you want.

You can get the value () and use it as a number or even better, just keep the money and do your operations. You can check the documentation here .

0
source

Source: https://habr.com/ru/post/1388268/


All Articles