What is the regular expression for a decimal with a precision of 2?
Valid examples:
123.12
2
56754
92929292929292.12
0.21
3.1
Invalid examples:
12.1232
2.23332
e666.76
The decimal point may be optional, and integers may also be included.
Valid regex tokens vary by implementation. A generic form is:
[0-9]+(\.[0-9][0-9]?)?
More compact:
\d+(\.\d{1,2})?
Both assume that both have at least one digit before and one after the decimal place.
To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):
^\d+(\.\d{1,2})?$
To match numbers without a leading digit before the decimal (.12) and whole numbers having a trailing period (12.) while excluding input of a single period (.), try the following:
^(\d+(\.\d{0,2})?|\.?\d{1,2})$
Added
Wrapped the fractional portion in ()? to make it optional. Be aware that this excludes forms such as 12. Including that would be more like ^\d+\\.?\d{0,2}$.
Added
Use ^\d{1,6}(\.\d{1,2})?$ to stop repetition and give a restriction to whole part of the decimal value.
^[0-9]+(\.[0-9]{1,2})?$
And since regular expressions are horrible to read, much less understand, here is the verbose equivalent:
^ # Start of string
[0-9]+ # Require one or more numbers
( # Begin optional group
\. # Point must be escaped or it is treated as "any character"
[0-9]{1,2} # One or two numbers
)? # End group--signify that it's optional with "?"
$ # End of string
You can replace [0-9] with \d in most regular expression implementations (including PCRE, the most common). I've left it as [0-9] as I think it's easier to read.
Also, here is the simple Python script I used to check it:
import re
deci_num_checker = re.compile(r"""^[0-9]+(\.[0-9]{1,2})?$""")
valid = ["123.12", "2", "56754", "92929292929292.12", "0.21", "3.1"]
invalid = ["12.1232", "2.23332", "e666.76"]
assert len([deci_num_checker.match(x) != None for x in valid]) == len(valid)
assert [deci_num_checker.match(x) == None for x in invalid].count(False) == 0
To include an optional minus sign and to disallow numbers like 015 (which can be mistaken for octal numbers) write:
-?(0|([1-9]\d*))(\.\d+)?
For numbers that don't have a thousands separator, I like this simple, compact regex:
\d+(\.\d{2})?|\.\d{2}
or, to not be limited to a precision of 2:
\d+(\.\d*)?|\.\d+
The latter matches
1
100
100.
100.74
100.7
0.7
.7
.72
And it doesn't match empty string (like \d*.?\d* would)
I use this one for up to two decimal places:
(^(\+|\-)(0|([1-9][0-9]*))(\.[0-9]{1,2})?$)|(^(0{0,1}|([1-9][0-9]*))(\.[0-9]{1,2})?$)
passes:
.25
0.25
10.25
+0.25
doesn't pass:
-.25
01.25
1.
1.256
^[0-9]+(\.([0-9]{1,2})?)?$
Will make things like 12. accepted. This is not what is commonly accepted but if in case you need to be “flexible”, that is one way to go. And of course [0-9] can be replaced with \d, but I guess it’s more readable this way.
Try this
(\\+|-)?([0-9]+(\\.[0-9]+))
It will allow positive and negative signs also.
preg_match("/^-?\d+[\.]?\d\d$/", $sum)
In general, i.e. unlimited decimal places:
^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$.
Main answer is WRONG because it valids 5. or 5, inputs
this code handle it (but in my example negative numbers are forbidden):
/^[0-9]+([.,][0-9]{1,2})?$/;
results are bellow:
true => "0" / true => "0.00" / true => "0.0" / true => "0,00" / true => "0,0" / true => "1,2"
true => "1.1"/ true => "1" / true => "100" true => "100.00"/ true => "100.0" / true =>
"1.11" / true => "1,11"/ false => "-5" / false => "-0.00" / true => "101" / false =>
"0.00.0" / true => "0.000" / true => "000.25" / false => ".25" / true => "100.01" /
true => "100.2" / true => "00" / false => "5." / false => "6," / true => "82" / true =>
"81,3" / true => "7" / true => "7.654"
Won't you need to take the e in e666.76 into account?
With
(e|0-9)\d*\d.\d{1,2)
adding my answer too, someone might find it useful or may be correct mine too.
function getInteger(int){
var regx = /^[-+]?[\d.]+$/g;
return regx.test(int);
}
alert(getInteger('-11.11'));
This worked with me:
(-?[0-9]+(\.[0-9]+)?)
Group 1 is the your float number and group 2 is the fraction only.
I tried one with my project.
This allows numbers with + | - signs as well.
/^(\+|-)?[0-9]{0,}((\.){1}[0-9]{1,}){0,1}$/
Chrome 56 is not accepting this kind of patterns (Chrome 56 is accpeting 11.11. an additional .) with type number, use type as text as progress.
This will allow decimal with exponentiation and upto 2 digits ,
^[+-]?\d+(\.\d{2}([eE](-[1-9]([0-9]*)?|[+]?\d+))?)?$
Demo
function DecimalNumberValidation() {
var amounttext = ;
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
}
function will validate any decimal number weather number has decimal places or not, it will say "Right Number" other wise "Please enter only numbers into amount textbox." alert message will come up.
Thanks... :)
Related
I need an expression to validate numbers between 1.0 to 4.5 but it's not working precisely for it.
Expression I'm using: /^[1-4]{0,1}(?:[.]\d{1,2})?$/
Requirement is to only accept value between 1.0 to 4.5
but
buildInserForm(): void {
this.insertLeavesForm = this.fb.group({
**your text**
hours: [
{ value: 4.5, disabled: true },
[
Validators.required,
Validators.pattern(**/^[1-4]{0,1}(?:[.]\d{1,2})?$/**),
],
],
});
}
Currently restricting the numbers from 1.0 to 4.0, But the issue comes in decimal points, it shows an error if entered any number between 6-9 in decimal places, like 1.7,2.8, 3.9.
acceptance criteria are 1.0 to 4.5.
This image shows that value is getting entered to multiple decimal places which is wrong,
Only single decimal place value is required.
Regex are pretty bad to check number ranges. Should it consider non decimal numbers? What if there is more than one decimal point? What if you should ever want to increase/decrease range? Here's more on the topic: Regular expression Range with decimal 0.1 - 7.0
I would suggest simple min/max Validators. Plus this would also let you control if user value is below or above criteria, letting you to display custom error messages appropriately, for example. Whereas regex will simply evaluate to true/false.
[
Validators.required,
Validators.min(1),
Validators.max(4.5),
Validators.maxLength(3)
]
You may use the following regex pattern:
^(?:[1-3](?:\.\d{1,2})?|4(?:\.(?:[0-4][0-9]|50?)?))$
Demo
This regex pattern says to match:
^ start of the input
(?:
[1-3] match 1-3
(?:\.\d{1,2})? followed by optional decimal and 1 or 2 digits
| OR
4 match 4
(?:
\. decimal point
(?:[0-4][0-9]|50?)? match 4.00 to 4.49 or 4.5 or 4.50
)
)
$ end of the input
This is a regex that I created.
pattern(/^[1-3]{0,1}(?:[.][0-9]{0,1})?[4]{0,1}(?:[.][0-5]{0,1})?$/)
Explaination
/^[1-3]{0,1}(?:[.][0-9]{0,1})?[4]{0,1}(?:[.][0-5]{0,1})?$/
/^ start of the input
[1-3] First input to be taken between
{0,1} This shows how many times it can be repeated
( Parenthesis shows next entered digit is optional
? Question mark is for using digit zero or once
:[.] This is for what the next Character would be eg ".", "#"
[0-9] input to be taken between.
{0,1} This shows how many times it can be repeated.
) Option part closes
? Question mark is for using digit zero or once.
[4] This shows what can be other input that can be taken
{0,1} How many times it can be use , SO in this case 0 or 1 times
(?:[.] There after again same option part with decimal point
decimal value of 4and its limitation for 0 to 5
[0-5] This is to set limitation 0-5 as per our requirement
{0,1} Its existence 0 or 1 times
) Close of optional part.
? Thereafter showing the existence of an optional part once or twice.
$/ Shows to match expression after it.
I'm trying to understand regex, and I want to prevent entering numbers starting with 550, if length is 8, or starting with 393 if length is 5.
Tried it here (https://regex101.com/) and the correct expression is shown below
^((?!550)\d{8}|(?!393)\d{5})$
but the mask in my code works in «online» mode, and for some reason allows only numbers starting with 550 or 393, the rest of the input is forbidden (can't even enter 10000). How to remake this expression?
I suggest not to tackle this problem with regular expressions. There is no easy way to express "any string except for this particular string".
My implementation:
let accept = function (v) {
v = v.toString();
if (v.substr(0, 3) === '550')
return v.length !== 8;
else if (v.substr(0, 3) === '393')
return v.length !== 5;
return true;
}
Testcases:
>> accept(12)
true
>> accept(12345678)
true
>> accept(55045678)
false
>> accept(55145678)
true
>> accept(39345)
false
>> accept(39445)
true
>> # special case
>> accept(550 * 10e155)
true
>> (550 * 10e155).toString() # reason
"5.5e+158"
This implementation will also work for very large numbers, just because very large integers are represented in exponential representation.
If you are still sure, you want to use regular expressions, here you go:
let accept = (v) => ((/^((?!550)\d{8}|(?!393)\d{5}|\d{0,4}|\d{6,7}|\d{9,})$/).exec(v) !== null)
You need to define alternation paths for the regular expression which will accept the string if it has length not equal to 5 and 8.
>> accept(12)
true
>> accept(12345678)
true
>> accept(55045678)
false
>> accept(55145678)
true
>> accept(39345)
false
>> accept(39445)
true
>> accept(550 * 10e155)
false
This implementation fails, because you need to properly implement the floating point representation of numbers in Javascript in order to accept large numbers. This is tedious. I don't recommend this approach.
I think your regex is wrong. It does not even allow matching numbers with length different to 5 or 8.
You may want to try this: ^(?:(?!550)\d{8}|(?!393)\d{5}|(?!\d{5}$|\d{8}$)\d+)$
Demo
Explained:
^ # begin of line/string
(?: # group of options (separated by '|'
(?!550)\d{8} # 8 digits not starting by 550
| (?!393)\d{5} # 5 digits not starting by 393
| (?!\d{5}$|\d{8}$) \d+ # some digits that must not be 5 and 8 and then end of line (5 and 8 should be treated above)
)
$ # end of line/string
If you also want to allow big numbers as in scientific notation, use this instead: ^(?:.*e\+.*|(?!550)\d{8}|(?!393)\d{5}|(?!\d{5}$|\d{8}$)\d+)$
Demo
It basically adds .*e\+.* as an option (searches for e followed by +)
I am trying to build a regex expression with this requirement .
Requirement :
Max length - 5(inc decimal dot if is a decimal number)
Decimal precession - max 2 digits (if it is a decimal numer ).
Number - need not to be a decimal number (not mandatory)
Code:
<script>
function myFunction() {
var regexp = /^(?!\.?$)\d{0,5}(\.\d{0,2})?$/;
var num = 12345.52; // i will test here indiffernt ways
var n = regexp.test(num)
document.getElementById("demo").innerHTML = n; // returns true or false
}
</script>
Output should look like :
12345.52 -->It should return false as length is 8 inc dot but it returns true
123456.52 --> false . I came to know d{0,5} is looking for before decimal
12.45 --> true . Perfect one (length 5 , precession 2 )
12345 --> true . Perfect one (length 5 , precession- not madatory)
I am hoping to build a regex expression satisfies all the above scenarios .
Reference : Click Here
You could try the below regex which uses positive lookahead assertion.
^(?=.{1,5}$)\d+(?:\.\d{1,2})?$
DEMO
Explanation:
^ Asserts that we are at the start.
(?=.{1,5}$) Asserts that the length must be from 1 upto 5.
\d+ Allows one or more digits.
(?:\.\d{1,2})? Optional decimal part with the allowable digits after the decimal point must be one or two.
$ Asserts that we are at the end of the line.
I need a regex to match the following inputs:
.25
.50
.75
1.25. 1.50, 1.75 are allowed (increments of .25)
(2.0/2.00, 3.0/3.00, 4.0/4.00, 5.0/5.00 - not allowed)
The integer parts allowed are 1-9
Hence 10.00 or 10.25... are not allowed
Special inputs not allowed are: 0, 0.0
The whole numbers 1,2,3,4,5,6, 7, 8 and 9 are allowed while 1.0/1.00,
2.0/2.00, 3.0/3.00...and so on are not allowed
Also, no, positive or negative signs before the number are allowed.
Hence
0.25, 0.50, 0.75 should not be allowed (of course after .75, only 1 is allowed)
so far the regular expression(s) that I have to satisfy the above conditions is:
/^[-+]?[0-9](\.[2|5|7]{1}[5|0]{1})?$/;
In my javascript I have:
var catchfloat5 = /^[-+]?[0-9](\.[2|5|7]{1}[5|0]{1})?$/;
var catchint2 = /^[1-9]$/;
the second regular expression is for matching integers 1-9.
and in the code I do:
if(inputHours.match(catchfloat5) || inputHours.match(catchint2) ) {
//alert("Correct, you entered float or an int");
return true;
}
The above code appears to do the job, but fails, because it allows the following inputs:
0.25
0.50
0.75
It does match 1.25, 1.50, 1.75 and so on.
How would I correct my regular expression to match: .25, .50 and .75?
I think the problem I have is: I do have a regular expression that might match negative decimal numbers also. When I try to get rid of the positive and negative symbols,
I am breaking the expression.
I do have trouble understanding the role of the ? character also.
And my research comes from:
http://www.regular-expressions.info/quickstart.html
What I am trying to accomplish is:
A regular expression that matches the inputs I described above
and also to learn a few fundaments of regular expressions in the process.
Just to be clear, you are wanting to match any multiple of 0.25 between 1 and 9.75 inclusive, where integers must not have the .00 while halves must have .50?
If so, your regex is:
/^[1-9](?:\.25|\.50|\.75|)$/
To explain, this allows any number between 1 and 9 as the integer part, then one of .25, .50, .75 or nothing.
If this is not what you were after, then please clarify your question because it took several minutes and multiple attempts to understand this much!
Try the following regex:
/^(?:[1-9]|[1-9]?\.(?:25|50|75))$/
It matches
Any integer 1-9 other than zero
1-9 or empty string followed by fractions .25, .50, .75, up to any number; leading zeroes not allowed
If you want to match more digits, and optional leading signs, you can do
/^[-+]?(?:[1-9][0-9]*|(?:[1-9][0-9]*)?\.(?:25|50|75))$/
Here is an example of what you can try:
function match(n) {
if (n.match(/^(|[1-9])\.(25|50|75)$/)) { return true; }
return false;
}
console.log(match('1.25')); // true
console.log(match('0.25')); // false
console.log(match('.75')); // true
console.log(match('2.70')); // false
console.log(match('2.751')); // false
console.log(match('12.75')); // false
console.log(match('2.00')); // false
/* explanation
^ starts from
(|[1-9]) nothing or a Number between 1 & 9
\. literal dot/point
(25|50|75) either 25 or 50 or 75
$ end here
*/
Here is the Fiddle
What I want is, there is a textbox with maximum length of 5. The values allowed are..
any integer // for example 1, 3, 9, 9239 all are valid
real number, with exaclty one point after decimal // eg. 1.2, 93.7 valid and 61.37, 55.67 invalid
it is also allowed to enter only decimal and a digit after that, that is .7 is valid entry (would be considered as 0.7)
I found this page, http://www.regular-expressions.info/refadv.html
So what I thought is that
There is a digit
If there is a digit and a decimal after that, there must be one number after that
If there is no digit there must be a decimal and a digit after that
So, the regex I made is..
a single digit one or more => /d+
an optional decimal point followed by exactly one digit => (?:[.]\d{1})?
if first condition matches => (?(first condition) => (?((?<=\d+)
then, match the option decimal and one exact digit =>(?((?<=\d+)(?:[.]\d{1})?
else => |
find if there is a decimal and one exact digit => (?:[.]\d{1}){1}
check the whole condition globally => /gm
overall expression =>
(?(?<=\d+)(?:[.]\d{1}){1}|(?:[.]\d{1}){1})+/gm
But it doesn't outputs anything..
Here's the fiddle
http://jsfiddle.net/Fs6aq/4/
ps: the pattern1 and pattern2 there, are related to my previous question.
Maybe you are complicating things too much. I did a quick test and unless I'm missing something this regex seems to work fine:
/^\d*\.?\d$/
Demo: http://jsbin.com/esihex/4/edit
Edit: To check the length you can do it without regex:
if ( value.replace('.','').length <= 5 && regex.test( value ) ) {
...
}
Notice that I used replace to remove the dots so they don't count as characters when getting the length.
You can try the following pattern:
/^\d{0,4}\.?\d$/
It seems to fulfil all your requirements:
> /^\d{0,4}\.?\d$/.test(".4")
true
> /^\d{0,4}\.?\d$/.test(".45")
false
> /^\d{0,4}\.?\d$/.test("1234.4")
true
> /^\d{0,4}\.?\d$/.test("12345.4")
false
> /^\d{0,4}\.?\d$/.test("12345")
true
> /^\d{0,4}\.?\d$/.test("123456")
false
This pattern assumes that the number can have a maximum of five digits and an optional decimal point.
If the maximum length of five includes the optional decimal point then the pattern is slightly more complex:
/^(?:\d{1,5}|\d{0,3}\.\d)$/
The first part of the group deals with integer numbers of the required length, the second option of the group deals with real numbers which maximum length (including the decimal point) is five.
Consider this code:
var checkedString = "45.3 fsd fsd fsdfsd 673.24 fsd63.2ds 32.2 ds 32 ds 44 fasd 432 235f d653 dsdfs";
checkedString = " "+checkedString;
var results = checkedString.match(/[\s]{1}(\d+\.*\d{1})(?![\d\.\w])+/gm);
results.map(function(result) {
return result.trim();
});
Couldn't make it in other way because in JS (?<= (lookbehind) regexp is not working.
This will be returned:
["45.3","32.2","32","44","432"]
So probably it's what you've expected.
I don't know what are you trying to do with those conditionals in your regex. I also looked at your jsfiddle, which outputs nothing for me. But I made a two versions of a regex that matches the correct values for the textbox, which are ^(?!(.{6,}))(?:[1-9]\d*)*(?:\.\d*[1-9])?$ and ^(?!(.{6,}))(?:\d*)*(?:\.\d*)?$.
The first disallows to start with zero, or end with zero after the decimal.
Comment if you need explanation of the regex.