简体   繁体   中英

Use regex in Javascript to get cents

I am trying to formulate a regex expression in JavaScript to get the cents form a number that has a decimal point. For example, an expression that can get 27 from 454.2700000 . I know how to do this with split and substring but is there an easier way using just a regular expression. Thanks

The following parses out two digits after the decimal point:

/\.(\d{2})/
  • \\. means a dot
  • \\d means a digit
  • {2} means two of them
  • () to capture this part of the match

To get the match, use .exec and [1] :

/\.(\d{2})/.exec("454.2700000")[1]; // "27"

If you really have a number and you want a number, why use strings?

var n=454.27;
var cents=Math.round(n*100)%100;

If n is a numeric string, multiplication converts it to a number:

var n= '454.270000';
var cents=Math.round(n*100)%100;

以下正则表达式将返回您想要的内容:

/(?:\.)(\d\d)/.exec(454.2700000)[1]

You could do a regex test

/\.(\d+)$/.test(454.2700000)

and get your cents here, parseInt(RegExp.$1, 10) . Parsing the integer strips the zeroes.

Or if you always want two decimal places, replace my \\d+ with pimvbd's \\d{2} and then you can just to RegExp.$1 without the parseInt.

You can see it here http://jsfiddle.net/nickyt/qbsfY

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