ajay ajay - 4 years ago 90
Javascript Question

Javascript regular expression if no digit specified before the period (.)

I have tried following expression which works fine to allow only 2 decimal places:

/^[0-9]+(\.[0-9]{1,2})?$/


But it's not considering the value like ".34" or ".5" as there isn't any digit before the period.
How can I update my expression so that, it should take digit "0" before period if nothing is specified before period.
so .34 => 0.34 with valid 2 decimal places expression.

Answer Source

You can use this regex:

/^\d*\.?\d{1,2}$/

RegEx Demo


If you want to format decimal numbers up to 2 decimal points then use toFixed:

var n = ".34";
var str = parseFloat(n).toFixed(2) // will do rounding as well
//=> 0.34
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download