简体   繁体   中英

Round number to two decimal places and delete any other decimal points

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM