EN
JavaScript - float regular expression
4
points
In this short article, we would like to show how in a simple way check if the text is a float number using regular expressions in JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const expression = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
const isFloat = (text) => !!text.match(expression);
// Usage example:
console.log(isFloat('123')); // true
console.log(isFloat('3.14')); // true
console.error(isFloat('abc')); // false
console.error(isFloat('a123b')); // false
Detailed example
Example in this section prints error messages only when incidated number is incorrect.
// ONLINE-RUNNER:browser;
const expression = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
// Where:
// ^ <- text matching since begining
// [+-]? <- optional sign before float number e.g. + or -
// (?:\d+(?:\.\d*)?|\.\d+) <- integer number, e.g. 123
// or integer number with dot between, e.g. 0.123
// or integer number with dot before, e.g. .123
// or integer number with dot after, e.g. 123.
// (?:[eE][+-]?\d+)? <- e or E with optional sign and integer number
// e.g. e10, E10, e-10, E-10, e+10, E+10
// $ <- text matching up to ending
const isFloat = (text) => !!text.match(expression);
// Testing section (printing only if error detected):
const values = [
'123', '-123', '+123', // integer numbers
'123.0', '-123.0', '+123.0', // optional sign + integer number with dot between
'0.123', '-0.123', '+0.123', // optional sign + integer number with dot between
'3.141', '-3.141', '+3.141', // optional sign + integer number with dot between
'.123', '-.123', '+.123', // optional sign + integer number with dot before
'123.', '-123.', '+123.', // optional sign + integer number with dot after
'0.1e10', '0.1e-10', '0.1e+10', // scientific notation with e
'0.1E10', '0.1E-10', '0.1E+10' // scientific notation with E
];
for (const value of values) {
if (!isFloat(value)) {
console.error(`${value} is not compatible with float number!`);
}
}