문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top