Question

I'm trying to use Javascript to verify that user input is a valid monetary (dollars and cents) amount, with no more than two digits to the right of the decimal point.

Shifting left, then performing a modulo 1 fails because of inherent floating-point issues:

(parseFloat("19.99") * 100) % 1 // Returns 0.9999999999997726

I'm aware of the BigDecimal library, but I'm not sure that converting to BigDecimal and then doing the validation would be the right approach, since it could cover up invalid inputs as well as floating-point issues.

As it stands, my workaround is to test the raw (string) input against the following regex:

/^\d*((\.\d{0,2})?)$/

Is this sufficient to guarantee that the input is a valid float in currency format? And if not, is there a math-based way to do the validation?

Was it helpful?

Solution

if you don't need to use RegExp, let JS's math do the heavy-lifting:

 var n=myInput.value;
 if(!n || +(+n || 0).toFixed(2) != +n) {  
   alert("real numbers only!"); 
   myInput.select(); 
 }

the validation routine part is made up and poor UX, but the math is solid and bullet-proof.

OTHER TIPS

Your regex will also match empty input, which is not right.

Try this regex instead:

^(?=[^.])\d*(?:\.\d{0,2})?$

Working Demo

  • (?=[^.]) is a lookahead that will make sure at least one non-dot character is there in input to avoid matching empty string.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top