EN
TypeScript - float regular expression
0 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 TypeScript.
Quick solution:
xxxxxxxxxx
1
const expression: RegExp = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
2
3
const isFloat = (text: string): boolean => !!text.match(expression);
4
5
6
// Usage example:
7
8
console.log(isFloat('123')); // true
9
console.log(isFloat('3.14')); // true
10
console.error(isFloat('abc')); // false
11
console.error(isFloat('a123b')); // false
Example in this section prints error messages only when incidated number is incorrect.
xxxxxxxxxx
1
const expression: RegExp = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/;
2
3
// Where:
4
// ^ <- text matching since begining
5
// [+-]? <- optional sign before float number e.g. + or -
6
// (?:\d+(?:\.\d*)?|\.\d+) <- integer number, e.g. 123
7
// or integer number with dot between, e.g. 0.123
8
// or integer number with dot before, e.g. .123
9
// or integer number with dot after, e.g. 123.
10
// (?:[eE][+-]?\d+)? <- e or E with optional sign and integer number
11
// e.g. e10, E10, e-10, E-10, e+10, E+10
12
// $ <- text matching up to ending
13
14
const isFloat = (text: string): boolean => !!text.match(expression);
15
16
17
// Testing section (printing only if error detected):
18
19
const values: string[] = [
20
'123', '-123', '+123', // integer numbers
21
22
'123.0', '-123.0', '+123.0', // optional sign + integer number with dot between
23
'0.123', '-0.123', '+0.123', // optional sign + integer number with dot between
24
'3.141', '-3.141', '+3.141', // optional sign + integer number with dot between
25
26
'.123', '-.123', '+.123', // optional sign + integer number with dot before
27
'123.', '-123.', '+123.', // optional sign + integer number with dot after
28
29
'0.1e10', '0.1e-10', '0.1e+10', // scientific notation with e
30
'0.1E10', '0.1E-10', '0.1E+10' // scientific notation with E
31
];
32
33
for (const value of values) {
34
if (!isFloat(value)) {
35
console.log(`${value} is not compatible with float number!`);
36
}
37
}