开发者

jQuery pull currency without dollar sign

I have a tag that has a price in it (ie. $150.00). I want to use jQuery to pull only the text va开发者_JAVA百科lues without the dollar sign ($).

<div>
  $150.00
</div>

I want to output the above as 150.00


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

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

Note that in the case of your exact example (with that spacing) the blank spaces will not be removed. If you're going on to use the string as a number (via parseFloat for example) that won't matter, but if you're wanting to use it as text somewhere else, you may want to remove white space with jQuery's .trim.

Update - based on comments

replace returns a String. Once you have that string, you can parse it into a Number with parseFloat (or parseInt, but you're working with floating point numbers):

var convertedToNumber = parseFloat(price);

Now that you've got a number, you can perform mathematical operations on it:

var percentage = convertedToNumber * 0.95;


Use of replace is better but I can suggest that you can remove any currency symbol from the string like

$ 150.00
Fr. 150.00
€ 689.00

I have tested for above three currency symbols .You can do it for others also.

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

Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as

console.log('price : '+price);

output = price : .150.00

which is wrong so you check the index of "." then split that and get the proper result.

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


Would $('div').text().replace('$', ''); work your purposes?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜