Reputation: 1143
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
Upvotes: 1
Views: 1904
Reputation: 104780
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;
Upvotes: 1
Reputation: 6981
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
Upvotes: 0
Reputation: 154838
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 matchTo get the match, use .exec
and [1]
:
/\.(\d{2})/.exec("454.2700000")[1]; // "27"
Upvotes: 3
Reputation: 8269
The following regex will return you what you want:
/(?:\.)(\d\d)/.exec(454.2700000)[1]
Upvotes: 0