Validate decimal numbers in JavaScript - IsNumeric()
@Joel's answer is pretty close, but it will fail in the following cases:
// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;
// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;
Some time ago I had to implement an IsNumeric
function, to find out if a variable contained a numeric value, regardless of its type, it could be a String
containing a numeric value (I had to consider also exponential notation, etc.), a Number
object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. +true == 1;
but true
shouldn't be considered as "numeric"
).
I think is worth sharing this set of +30 unit tests made to numerous function implementations, and also share the one that passes all my tests:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
P.S. isNaN & isFinite have a confusing behavior due to forced conversion to number. In ES6, Number.isNaN & Number.isFinite would fix these issues. Keep that in mind when using them.
Update :
Here's how jQuery does it now (2.2-stable):
isNumeric: function(obj) {
var realStringObj = obj && obj.toString();
return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;
}
Update :
Angular 4.3:
export function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}
Validate decimal numbers in JavaScript - IsNumeric()
@Joel's answer is pretty close, but it will fail in the following cases:
// Whitespace strings:
IsNumeric(' ') == true;
IsNumeric('\t\t') == true;
IsNumeric('\n\r') == true;
// Number literals:
IsNumeric(-1) == false;
IsNumeric(0) == false;
IsNumeric(1.1) == false;
IsNumeric(8e5) == false;
Some time ago I had to implement an IsNumeric
function, to find out if a variable contained a numeric value, regardless of its type, it could be a String
containing a numeric value (I had to consider also exponential notation, etc.), a Number
object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. +true == 1;
but true
shouldn't be considered as "numeric"
).
I think is worth sharing this set of +30 unit tests made to numerous function implementations, and also share the one that passes all my tests:
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
P.S. isNaN & isFinite have a confusing behavior due to forced conversion to number. In ES6, Number.isNaN & Number.isFinite would fix these issues. Keep that in mind when using them.
Update :
Here's how jQuery does it now (2.2-stable):
isNumeric: function(obj) {
var realStringObj = obj && obj.toString();
return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0;
}
Update :
Angular 4.3:
export function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}
Check if a number has a decimal place/is a whole number
Using modulus will work:
num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5
Note that this is based on the numerical value of the number, regardless of format. It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:
'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5
How to properly validate decimal values?
You could test if the string does not start with 2 or more zeroes
^(?!00+\.)[0-9]+\.?[0-9]*$
Regex demo
Note that your pattern ^[0-9]+\.?[0-9]+$
matches at least 2 digits as only the comma is optional.
const rgx = /^(?!00+\.)[0-9]+\.?[0-9]*$/
const cases = ["1234",
"12.34",
"0.123",
"000045",
"000.45",
".45685",
"5..454",
"55874.",
"000000",
"0.0."
]
cases.forEach(s => console.log(`${s} --> ${rgx.test(s)}`));
Javascript validate number commas and decimal
Try using regex instead
const isNumber = x => !!`${x}`.match(/^\d*(,\d{3})*(\.\d*)?$/)
console.log(isNumber("1,093,222.04")) // true
console.log(isNumber("0.232567")) // true
console.log(isNumber("1267")) // true
console.log(isNumber("1,093,22.04")) // false
console.log(isNumber("1.282,04")) // false
console.log(isNumber("abcd124")) // false
Do note that the function must take in a string, since if you pass in the number itself, the commas ,
will split the "number" into different parameters
Javascript Check if one decimal number is a multiple of another decimal number
I'm no math wiz so take this with a grain of salt. This appears to be working for me. I tried all the example values in your post and they are all passing as multiples. May or may not work for all values.
const numA = 0.0005;
const numB = 0.0001;
if (Number.isInteger(Math.fround(numA / numB))) {
console.log('is multiple');
} else {
console.log('not a multiple');
}
Validate decimal in javascript
Well, this is what I'd do, If I understand correctly.
This addresses a few issues:
- JavaScript doesn't like the numeric value
00.01
. Use0.01
instead - use
parseFloat
on yourinput
value.parseInt
will round to an integer - return
true
if successful (not undefined)
function submitform4() {
var MIN = 0.01;
var MAX = 100.00;
var input = document.getElementById('AgeGrade');
var inputValue = parseFloat(input.value);
var is_valid = (MIN > inputValue || MAX < inputValue);
if (is_valid) {
input.value = inputValue.toFixed(2); // set to 2 decimal places
return true
} else {
alert(inputValue + ' is not between ' + MIN + ' and ' + MAX);
return false;
}
}
How to validate if a decimal number is in a sequence 0.001, 0.002, ..., 2.048
Note that doing math with floating point numbers can be inaccurate, so verifying them (which requires an exact value) might not work well.
So, you can multiply your number, so that it's an integer, to avoid precision issues and then you can even use your solution on it.
Here's a purely mathematical solution:
const validate = (toVerify, initial) => {
const num = toVerify / initial //division is like multiplication with the reciprocal!
return (num & num - 1) == 0
};
console.log(validate(8, 1)) //true
console.log(validate(0.08, 0.01)) //true
console.log(validate(0.008, 0.001)) //true
console.log(validate(0.016, 0.001)) //true
console.log(validate(0.08, 0.001)) //false
Related Topics
Use of 'Prototype' Vs. 'This' in JavaScript
How Does JavaScript .Prototype Work
Safely Turning a Json String into an Object
How to Filter Object Array Based on Attributes
How to Create an Object Property from a Variable Value in JavaScript
Json: Why Are Forward Slashes Escaped
How to Add 1 Day to Current Date
Recursive Function Returns Undefined
JavaScript Check If Variable Exists (Is Defined/Initialized)
How to Get the Full Object in Node.Js'S Console.Log(), Rather Than '[Object]'
How to Add Options to a Select from a JavaScript Object With Jquery
How to Reload a Page Using JavaScript
Fastest Way to Duplicate an Array in JavaScript - Slice Vs. 'For' Loop
JavaScript Variable Number of Arguments to Function
Can You Bind 'This' in an Arrow Function