Only decimal number validation in javascript
The accepted answer failed your test #7 and I guess it's because you changed your mind. So this is a response to the accepted answer, with which I had issues. Show During some projects I have needed to validate some data and be as certain as possible that it is a javascript numerical value that can be used in mathematical operations. jQuery, and some other javascript libraries already include such a function, usually called
First, the code above would return true if the argument was an array of length 1, and that single element was of a type deemed as numeric by the above logic. In my opinion, if it's an array then its not numeric. To alleviate this problem, I added a check to discount arrays from the logic
Of course, you could also use My second issue was that Negative Hexadecimal integer literal strings ("-0xA" -> -10) were not being counted as numeric. However, Positive Hexadecimal integer literal strings ("0xA" -> 10) were treated as numeric. I needed both to be valid numeric. I then modified the logic to take this into account.
If you are worried about the creation of the regex each time the function is called then you could rewrite it within a closure, something like this
I then took CMSs +30 test cases and cloned the testing on jsfiddle added my extra test cases and my above described solution. It may not replace the widely accepted/used answer but if this is more of what you are expecting as results from your isNumeric function then hopefully this will be of some help. EDIT: As pointed out by Bergi, there are other possible objects that could be considered numeric and it would be better to whitelist than blacklist. With this in mind I would add to the criteria. I want my isNumeric function to consider only Numbers or Strings With this in mind, it would be better to use
Test the solutions
How do you validate decimal numbers?A decimal number can start with dot also, like . 34, -. 12, so dot also can be at the first position. But a decimal number should have only one dot.
How do you check if a number has a decimal in JavaScript?function number_test(n) { var result = (n - Math. floor(n)) !== 0; if (result) return 'Number has a decimal place.
How do I limit the number of decimals in JavaScript?To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places. This method: Rounds the number. Converts it into a string.
How do you validate decimal values in regex?A better regex would be /^\d*\.?\ d+$/ which would force a digit after a decimal point.. ^ - Beginning of the line;. \d* - 0 or more digits;. \.? - An optional dot (escaped, because in regex, . is a special character);. \d* - 0 or more digits (the decimal part);. $ - End of the line.. |