问题描述:

I have a javascript function that grabs some data from the current webpage the user is one, one thing it grabs is the contents of a element with the class name 'price'.

Currently I use:

price = price.replace(/[^\d.]/g, "");

Which will strip away anything else other than a number and decimal points from what was within the element (in theory leaving just the actual price). Most of the time this works well and you are left with something like 20.99 when the element had <br/>20.99 Is the price for example.

This works pretty well however on some websites what is left is actually a string with more than one decimal point so something like:

20.9999393.9374.028

What I need to then do is strip away everything after two decimal places after the first decimal point so the above would become

20.99

网友答案:

try this:

 var price = "20.9999393.9374.028";
 var nums = price.split(".");
 var num = nums[0] + '.' + nums[1].substr(0,2);

DEMO

相关阅读:
Top