Regex to validate decimals - javascript

I need to validate the integers with the below pattern. Integer part can have up to 5 characters and the fraction value can have up to 2 chars. (fraction value is optional). Leading + or - is also optional.
(+/-) mmmmm (5).nn (2)
Test data
Valid
-1
+1
1
+.1
-.1
.1
+11111.11
-11111.11
11111
Invalid
+111111.11
-111111.11
+11111.111
-11111.111
11111.111
111111.11
+1.
-1.
1.
This is what I currently use
[+-]?\d{0,5}\.?\d{1,2}?
Is this correct? Am I missing something obvious?
Here is the test case.
EDIT
If there is an additional constraint to have the number of digits from the scale is included in the precision.
For example DECIMAL(5, 2) defines numbers of the form 1234.5 whereas DECIMAL(5, 5) defines numbers of the form 1.2345. How should I change this?

Do:
^[+-]?(?:[0-9]{1,5})?(?:\.[0-9]{1,2})?$
^[+-]? matches + or - at start, optional
(?:[0-9]{1,5})? matches one to five digits, optional
(?:\.[0-9]{1,2})?$ matches a literal dot, followed by one or two digits at the end, optional. As the literal . is inside the non-captured group with the digits pattern following, it will only be matched when there are required digits afterwards
Demo

In Javascript, you can validate a number using
Number(n) === Number(n)
For any non-number values of n, like "abc" or [1, 2, 3], Number(n) will return NaN. Given that NaN !== NaN in any case, you can easily tell if n is a number.
Number constructor works fine with almost any form of number representation:
Number(123) // -> 123
Number('123') // -> 123
Number('+12e+3') // -> 12000
Number('-1.2e-3') // -> -0.0012
Number('--123') // -> NaN
However, if you are constrained to using regular expressions, it's very close to what you described:
Optional "+" or "-".
0 to 5 digits.
Optional "." and then 1 to 2 digits in decimal part. The whole part is optional, meaning that a single dot with no digits is invalid
And no exponential form.
That would be
/^[+-]?\d{0,5}(\.\d{1,2})?$/
so that
/^[+-]?\d{0,5}(\.\d{1,2})?$/.test(123) // -> true
/^[+-]?\d{0,5}(\.\d{1,2})?$/.test('123') // -> true
/^[+-]?\d{0,5}(\.\d{1,2})?$/.test('+123.45') // -> true
/^[+-]?\d{0,5}(\.\d{1,2})?$/.test('--123') // -> false
/^[+-]?\d{0,5}(\.\d{1,2})?$/.test('-123.456') // -> false
Please note that the part (\.\d{1,2})? is whole optional. In your case, either dot or two decimal digits are optional, so "123." would be a valid number. In Javascript, it is valid, though, so there shouldn't be any problem with that.

A slight modification in your regex works :
^[+-]?[0-9]{0,5}?(\.[0-9]{1,2})?$
or
^[+-]?\d{0,5}?(\.\d{1,2})?$
Demo1
Demo2

Related

regular expression no more than one digit

how to make a regular expression into one number (only numbers) and that it does not exceed 10 from 0 to 10
/^[1-9][1]*$/.test(message)
It doesn't work that way for me.
To specify the amount of a specific character use {} instead of [], in this case, as it is only one digit, you do not need to specify a count as 1 is default:
/^[0-9]$/.test(message)
I assume you mean you want to match a single digit between 0 and 10. If not please comment to clarify.
Hope this helps.
Assuming you only want integers or whole numbers, then use:
/^(?:[0-9]|10)$/
If you want to allow for decimals, then use:
/^(?:[0-9](?:\.\d+)?|10(?:\.0+)?)$/
The second regex says to match:
^ from the start of the number
(?:
[0-9] 0 to 9
(?:\.\d+)? any optional decimal component
| OR
10 match integer 10
(?:\.0+)? optional zero decimal only
)
$ end of the number

regex for age with 2 decimal points

What is regex for age with 2 decimal points value with max value 99.11
Valid examples:
1
12.01
16.06
20.11
Invalid examples:
.0
1.12 (decimal value should be <12)
1.13 (decimal value should be <12)
12.111
100.00 (2 digit before decimal point, max 99.11)
I have tried ^[0-9]\d{0,1}(\.\d[0-1]\d{0,1})*(,\d+)?$ regex but it is not following all criteria.
can anyone help me?
You can try with this pattern:
/^\d{1,2}(\.(0[0-9]|1[01]))?$/
var pattern = /^\d{1,2}(\.(0[0-9]|1[01]))?$/;
console.log(pattern.test('1'));
console.log(pattern.test('12.01'));
console.log(pattern.test('16.06'));
console.log(pattern.test('20.11'));
console.log(pattern.test('.0'));
console.log(pattern.test('1.12'));
console.log(pattern.test('1.13'));
console.log(pattern.test('12.111'));
console.log(pattern.test('100.00'));
Try this.
/^\d\d?(\.(0\d|1[01]))?$/
Description:
^\d\d? - from the start of the string, match 1 or 2 numbers
After that/those numbers, optionally match . plus 2 numbers
The two numbers must be 0 and any number, else 1 and 0 or 1
Anchor to the end of the string
You are missing the two different patterns of floating part, which must be handled with a |.
A character-optimal solution is ^\d{1,2}(\.[0]\d|\.1[01])?$.

Why is parseFloat('1/2') == 1 in Javascript

I am unable to understand this:
parseFloat('1/2') == 1 Not Expected
parseFloat(1/2) == 0.5 Expected
parseFloat('0.5') == 0.5 Expected
parseFloat(0.5) == 0.5 Expected
Is it some issue or am I doing something wrong? Also, how to get
parseFloat('1/2') == 0.5
As in doc mentioned parseFloat
parseFloat parses its argument, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.
so 1/2 treated as a string.
Not only that - this string does not contain a valid number representation in JavaScript.
Numbers in JavaScript may include -, 0-9, . and +e.
/ is not a part of it. Therefore - parseFloat parses all the characters that are legal as a number - which in your case is just the 1 part, and ignores rest.
1/2 in JavaScript is not a number, but an expression including 2 numbers and an operator (1 = num, / = operator, 2 = number). What can execute expressions?
You can use eval to calculate fractional form.
console.log(eval('2/3'))
Mind that eval is a dangerous function: using eval on user-input can lead to exploits.
parseFloat does not understand the / character as a division nor does it do an eval of the string input.
It simply stops looking when it encounters the character it doesn't understand and returns the correctly parsed first part:
console.log(
parseFloat("1/2"), // 1
parseFloat("3/2"), // 3
parseFloat("1kahsdjfjhksd2") // 1
)
If you do want to evaluate the string "1/2" to the number 0.5, you can use eval. Be careful, because using eval can be a security risk, slow and hard to debug.
console.log(
eval("1/2")
);
Not 100% sure. but if you play around with parseFloat a bit you will see that it tries to convert every number it finds to a float, but stops as soon as there is a unexpected value so :
parseFloat('1/asdf') == 1
but
parseFloat('0.5') == 0.5
So parse float does not calculate for you, but just parses every number it finds, until there is something non numerical.
Your parsing a string that will be converted to 1. If your string was only numbers (e.g. "0.5") them they would be converted correctly, but as it includes the '/', the automatic type conversion will not occur and it will remain as a string. When using numbers the expected behavior occurs, that is:
parseFloat(1/2) === 0.5 // true

Javascript regular expression if no digit specified before the period (.)

I have tried following expression which works fine to allow only 2 decimal places:
/^[0-9]+(\.[0-9]{1,2})?$/
But it's not considering the value like ".34" or ".5" as there isn't any digit before the period.
How can I update my expression so that, it should take digit "0" before period if nothing is specified before period.
so .34 => 0.34 with valid 2 decimal places expression.
You can use this regex:
/^\d*\.?\d{1,2}$/
RegEx Demo
If you want to format decimal numbers up to 2 decimal points then use toFixed:
var n = ".34";
var str = parseFloat(n).toFixed(2) // will do rounding as well
//=> 0.34
Use * instead of +
^[0-9]*(\.[0-9]{1,2})?$
+: Matches 1 or more of the preceding token.
*: Matches 0 or more of the preceding token.

RegEx to filter out all but one decimal point [duplicate]

i need a regular expression for decimal/float numbers like 12 12.2 1236.32 123.333 and +12.00 or -12.00 or ...123.123... for using in javascript and jQuery.
Thank you.
Optionally match a + or - at the beginning, followed by one or more decimal digits, optional followed by a decimal point and one or more decimal digits util the end of the string:
/^[+-]?\d+(\.\d+)?$/
RegexPal
The right expression should be as followed:
[+-]?([0-9]*[.])?[0-9]+
this apply for:
+1
+1.
+.1
+0.1
1
1.
.1
0.1
Here is Python example:
import re
#print if found
print(bool(re.search(r'[+-]?([0-9]*[.])?[0-9]+', '1.0')))
#print result
print(re.search(r'[+-]?([0-9]*[.])?[0-9]+', '1.0').group(0))
Output:
True
1.0
If you are using mac, you can test on command line:
python -c "import re; print(bool(re.search(r'[+-]?([0-9]*[.])?[0-9]+', '1.0')))"
python -c "import re; print(re.search(r'[+-]?([0-9]*[.])?[0-9]+', '1.0').group(0))"
You can check for text validation and also only one decimal point validation using isNaN
var val = $('#textbox').val();
var floatValues = /[+-]?([0-9]*[.])?[0-9]+/;
if (val.match(floatValues) && !isNaN(val)) {
// your function
}
This is an old post but it was the top search result for "regular expression for floating point" or something like that and doesn't quite answer _my_ question. Since I worked it out I will share my result so the next person who comes across this thread doesn't have to work it out for themselves.
All of the answers thus far accept a leading 0 on numbers with two (or more) digits on the left of the decimal point (e.g. 0123 instead of just 123) This isn't really valid and in some contexts is used to indicate the number is in octal (base-8) rather than the regular decimal (base-10) format.
Also these expressions accept a decimal with no leading zero (.14 instead of 0.14) or without a trailing fractional part (3. instead of 3.0). That is valid in some programing contexts (including JavaScript) but I want to disallow them (because for my purposes those are more likely to be an error than intentional).
Ignoring "scientific notation" like 1.234E7, here is an expression that meets my criteria:
/^((-)?(0|([1-9][0-9]*))(\.[0-9]+)?)$/
or if you really want to accept a leading +, then:
/^((\+|-)?(0|([1-9][0-9]*))(\.[0-9]+)?)$/
I believe that regular expression will perform a strict test for the typical integer or decimal-style floating point number.
When matched:
$1 contains the full number that matched
$2 contains the (possibly empty) leading sign (+/-)
$3 contains the value to the left of the decimal point
$5 contains the value to the right of the decimal point, including the leading .
By "strict" I mean that the number must be the only thing in the string you are testing.
If you want to extract just the float value out of a string that contains other content use this expression:
/((\b|\+|-)(0|([1-9][0-9]*))(\.[0-9]+)?)\b/
Which will find -3.14 in "negative pi is approximately -3.14." or in "(-3.14)" etc.
The numbered groups have the same meaning as above (except that $2 is now an empty string ("") when there is no leading sign, rather than null).
But be aware that it will also try to extract whatever numbers it can find. E.g., it will extract 127.0 from 127.0.0.1.
If you want something more sophisticated than that then I think you might want to look at lexical analysis instead of regular expressions. I'm guessing one could create a look-ahead-based expression that would recognize that "Pi is 3.14." contains a floating point number but Home is 127.0.0.1. does not, but it would be complex at best. If your pattern depends on the characters that come after it in non-trivial ways you're starting to venture outside of regular expressions' sweet-spot.
Paulpro and lbsweek answers led me to this:
re=/^[+-]?(?:\d*\.)?\d+$/;
>> /^[+-]?(?:\d*\.)?\d+$/
re.exec("1")
>> Array [ "1" ]
re.exec("1.5")
>> Array [ "1.5" ]
re.exec("-1")
>> Array [ "-1" ]
re.exec("-1.5")
>> Array [ "-1.5" ]
re.exec(".5")
>> Array [ ".5" ]
re.exec("")
>> null
re.exec("qsdq")
>> null
For anyone new:
I made a RegExp for the E scientific notation (without spaces).
const floatR = /^([+-]?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)$/;
let str = "-2.3E23";
let m = floatR.exec(str);
parseFloat(m[1]); //=> -2.3e+23
If you prefer to use Unicode numbers, you could replace all [0-9] by \d in the RegExp.
And possibly add the Unicode flag u at the end of the RegExp.
For a better understanding of the pattern see https://regexper.com/.
And for making RegExp, I can suggest https://regex101.com/.
EDIT: found another site for viewing RegExp in color: https://jex.im/regulex/.
EDIT 2: although op asks for RegExp specifically you can check a string in JS directly:
const isNum = (num)=>!Number.isNaN(Number(num));
isNum("123.12345678E+3");//=> true
isNum("80F");//=> false
converting the string to a number (or NaN) with Number()
then checking if it is NOT NaN with !Number.isNaN()
If you want it to work with e, use this expression:
[+-]?[0-9]+([.][0-9]+)?([eE][+-]?[0-9]+)?
Here is a JavaScript example:
var re = /^[+-]?[0-9]+([.][0-9]+)?([eE][+-]?[0-9]+)?$/;
console.log(re.test('1'));
console.log(re.test('1.5'));
console.log(re.test('-1'));
console.log(re.test('-1.5'));
console.log(re.test('1E-100'));
console.log(re.test('1E+100'));
console.log(re.test('.5'));
console.log(re.test('foo'));
Here is my js method , handling 0s at the head of string
1- ^0[0-9]+\.?[0-9]*$ : will find numbers starting with 0 and followed by numbers bigger than zero before the decimal seperator , mainly ".". I put this to distinguish strings containing numbers , for example, "0.111" from "01.111".
2- ([1-9]{1}[0-9]\.?[0-9]) : if there is string starting with 0 then the part which is bigger than 0 will be taken into account. parentheses are used here because I wanted to capture only parts conforming to regex.
3- ([0-9]\.?[0-9]): to capture only the decimal part of the string.
In Javascript , st.match(regex), will return array in which first element contains conformed part. I used this method in the input element's onChange event , by this if the user enters something that violates the regex than violating part is not shown in element's value at all but if there is a part that conforms to regex , then it stays in the element's value.
const floatRegexCheck = (st) => {
const regx1 = new RegExp("^0[0-9]+\\.?[0-9]*$"); // for finding numbers starting with 0
let regx2 = new RegExp("([1-9]{1}[0-9]*\\.?[0-9]*)"); //if regx1 matches then this will remove 0s at the head.
if (!st.match(regx1)) {
regx2 = new RegExp("([0-9]*\\.?[0-9]*)"); //if number does not contain 0 at the head of string then standard decimal formatting takes place
}
st = st.match(regx2);
if (st?.length > 0) {
st = st[0];
}
return st;
}
Here is a more rigorous answer
^[+-]?0(?![0-9]).[0-9]*(?![.])$|^[+-]?[1-9]{1}[0-9]*.[0-9]*$|^[+-]?.[0-9]+$
The following values will match (+- sign are also work)
.11234
0.1143424
11.21
1.
The following values will not match
00.1
1.0.00
12.2350.0.0.0.0.
.
....
How it works
The (?! regex) means NOT operation
let's break down the regex by | operator which is same as logical OR operator
^[+-]?0(?![0-9]).[0-9]*(?![.])$
This regex is to check the value starts from 0
First Check + and - sign with 0 or 1 time ^[+-]
Then check if it has leading zero 0
If it has,then the value next to it must not be zero because we don't want to see 00.123 (?![0-9])
Then check the dot exactly one time and check the fraction part with unlimited times of digits .[0-9]*
Last, if it has a dot follow by fraction part, we discard it.(?![.])$
Now see the second part
^[+-]?[1-9]{1}[0-9]*.[0-9]*$
^[+-]? same as above
If it starts from non zero, match the first digit exactly one time and unlimited time follow by it [1-9]{1}[0-9]* e.g. 12.3 , 1.2, 105.6
Match the dot one time and unlimited digit follow it .[0-9]*$
Now see the third part
^[+-]?.{1}[0-9]+$
This will check the value starts from . e.g. .12, .34565
^[+-]? same as above
Match dot one time and one or more digits follow by it .[0-9]+$

Categories

Resources