Amit Patil
Amit Patil

Reputation: 1993

JavaScript validation for numeric values

I want one validation in JavaScript so that a text boxt should allow to enter only numeric values in the following format:

4.25
4.50
2.00

and so on. There should be always 2 digits after the decimal point and 1 digit before the decimal point. If the user enters 2, it should display as 2.00. This is my requirement.

Upvotes: 1

Views: 396

Answers (1)

Sachin Shanbhag
Sachin Shanbhag

Reputation: 55479

For having only 2 digits after . you can use Number().toFixed(2) function in javscript

var num = Number(4).toFixed(2) will give you 4.00

var num = Number(4.1).toFixed(2) will give you 4.10

if you do not have number in place after ".", then toFixed will append 0 to your number.

For you second question, probably you can split your number on "." and check the first element is of length 1.

Upvotes: 1

Related Questions