Jquery pull out dollar signless currency

I have a tag in which there is a price (i.e. $ 150.00). I want to use jQuery to pull only text values ​​without a dollar sign ($).

<div> $150.00 </div> 

I want to output the above as 150.00

+4
source share
3 answers

You can use replace to replace the $ character with an empty string:

 var price = $("div").text().replace("$", ""); 

Please note that in the case of your exact example (with this interval), spaces will not be removed. If you intend to use the string as a number (for example, via parseFloat ), it does not matter, but if you want to use it as text in another place, you may need to remove the space using jQuery .trim .

Refresh - Based on Comments

replace returns a string. Once you have this line, you can parseFloat it into Number using parseFloat (or parseInt , but you work with floating point numbers):

var convertedToNumber = parseFloat(price);

Now that you have the number, you can perform mathematical operations on it:

var percentage = convertedToNumber * 0.95;

+18
source

Using a replacement is better, but I can assume that you can remove any currency symbol from a string, for example

 $ 150.00 Fr. 150.00 € 689.00 

I checked for three currency characters. You can do this for others.

 var price = $("div").text().replace(/[^\d\.]/g, ''); 

The above regex will remove anything that is not a digit or period. Thus, you can get a string without a currency symbol, but in the case of "Fr. 150.00", if you are a console for output, you will get the price as

 console.log('price : '+price); output = price : .150.00 

which is incorrect, so you are checking the index ".". then split it and get the correct result.

 if (price.indexOf('.') == 0) { price = parseFloat(price.split('.')[1]); }else{ price = parseFloat(price); } 
+5
source

Will there be $('div').text().replace('$', ''); work for your purposes?

0
source

All Articles