Javascript regex integer number with decimal - javascript

I am trying to write a regex for the following condition:
Allow to enter up to 1 decimal place and if I start with integer 0; the next has to be decimal otherwise any other number entered will remove the 0(integer)
The regex that I have provided is /(^$)|(^[0-9]+(\.([0-9]{1})?)?$)/ it accepts 1 decimal place but I am unable to achieve the remaining part.
Edit 1
passed numbers -->
1.3
4.5
0.4
Failed numbers ---->
004
If number starts with 0, next character must be a decimal only
Eg,
0.5 is a pass
005 is a failed

try this:
^([1-9]+\d*.?\d?)|^(0.\d)
If not, see comments and try to better exemplify

Try this regex:
^([0]{1}(\.[0-9]+))$|^([1-9]{1}|[1-9][0-9]+)$
ADJUSTED REGEX:
I have now adjusted the regex as required: all numbers that start with 0 MUST follow a comma, e.g. 0.2 or 0.0002 is accepted. 02 or 00002 is NOT accepted

OK, you want find integer number not start with 0, and find decimal?
Your code is: /(^$)|(^[0-9]+(\.([0-9]{1})?)?$)/
Case 1: integer [1-9]\d*
Case 2: decimal
//match 5.0
patt = \d+\.\d+
//Match 5.1xxxx, 5.2xxx, etc.
patt = \d+\.[1-9]\d*
//match 5.0xxx
patt = \d+\.0\d+
//combine all of them
patt = ([1-9]\d*|\d+\.[1-9]\d*|\d+\.0\d+)
//Final
patt = /(^$)|(([1-9]\d*|\d+\.[1-9]\d*|\d+\.0\d+)?$)/
I will explain some pattern above:
\d == [0-9] //match 1 character between 0 and 9
\d* == \d{0,} //match 0 or more character
\d+ == \d{1,} //match at least one character

Related

angularjs ng-pattern regex for 4 digits and 2 decimal

I am trying to create a Regex for a number with maximum 4 digits and if the input has decimal it has to have 2 digits - .20 and not .1.
tried:
ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" //fail for 666666, .10, .1
Examples for valid inputs:
100.10
100
3000.10
Example for invalid:
10000 //has more then 4 digits before decimal
100.1 //has only 1 digit after decimal
.10 //has no digits before decimal
Thanks for any help.
Use {#,#} to limit the number of digits to 1 to 4
Try
^[0-9]{1,4}(\.[0-9][0-9])?$
Use ( )? to make an optional two-digit decimal part
The problem with using the {1,2} is that it allows one or two digits, when you really only want two. And I assume you want to enforce a rule that if they have a ".", they must have two digits?
For example
var patt = /^[0-9]{1,4}(\.[0-9][0-9])?$/i
"1011.11".match(patt)!==null
"1011.1".match(patt)!==null
Returns
true
false
With gratitude to Sebastian Proske and Wiktor Stribiżew
For pointing out the need to escape the .

Regex for non negative and non zero for the format ###.##

I have a requirement to validate some inputs which should be in format ###.##
Invalid inputs are:
-11.10 ==> no negative
000.00 or 0 ==> 0 not allowed should be positive
Valid inputs are:
1
11
111
1.1
11.11
111.11
I have tried with the following regex ^([^-]\d{0,2}(.\d{1,2})?)$ which fulfills my requirements except it's accepting 0 which I don't want. How I can modify my regex so only 0's do not get matched?
Thanks For Help
Try
^(?=.*[1-9])\d{1,3}(?:\.\d\d?)?$
It should do it for you.
It starts with a positive look-ahead to make sure there's a digit other than 0 present.
Then it matches 1-3 digits, optionally followed by a . and 1-2 digits.
Your regex101 updated.
([0-9]){1,3}(\.[0-9]{1,2})? is the expression you are searching for.
([0-9]){1,3} = any number sequence with a length from 1 up to 3
(\.[0-9]{1,2})? = "?" maybe there is a float tail
(\.[0-9]{1,2}) = float tail must start with a dot and decimal numbers have to be up to 2
There is a way to except all zero sequences but it will waste your time for no reason, as you can simply check it with if myNum > 0.
It will work for negative values also, but this regex excludes them too.
^[1-9][0-9]*(\.[0-9]+)?$|^0\.[0-9]+$
This will work for you. It accepts all valid positive decimal numbers excluding 0.

Regex to check amount is greator then one

I have a regex
^(?=.*[1-9])\\d{0,5}(?:\\.\\d{0,2})?$
to check amount should be greater then 0 and it can contain maximum five digit before decimal and optional decimal and 2 digits after decimal.
Here (?=.*[1-9]) is to check there should be latest one occurrence of any digit from (1-9) in the string.
But I want modify it to check amount greater then one(1), so I want (?=.*[1-9]) to check only till the occurrence of the decimal point i.e. 0.1 it should return false.
Other condition should also fulfill.
Note : the count of digits before decimal is not fix, it will very from 1 to 5, so we can't modify it to (?=.{0,5}[1-9])
You can fix it by using this negation based regex:
^(?=[^.]*[1-9])\\d{0,5}(?:\\.\\d{0,2})?$
RegEx Demo
[^.]* before [1-9] will match any character except decimal point thus not allowing 0.45 as valid number.

Regex expression is not working?

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.

Currency validation

Please help with me writing a JavaScript Validation for currency/money field.
So please provide any regular expressions if u have :)
Also, for my region, don't need any currency symbols like '$' in the field.
Only decimals are to be included for validation as special chars., along with numbers.
You could use a regexp:
var regex = /^\d+(?:\.\d{0,2})$/;
var numStr = "123.20";
if (regex.test(numStr))
alert("Number is valid");
If you're not looking to be as strict with the decimal places you might find it easier to use the unary (+) operator to cast to a number to check it's validity:
var numStr = "123.20";
var numNum = +numStr; // gives 123.20
If the number string is invalid, it will return NaN (Not a Number), something you can test for easily:
var numStr = "ab123c";
var numNum = +numStr;
if (isNaN(numNum))
alert("numNum is not a number");
It will, of course, allow a user to add more decimal places but you can chop any extra off using number.toFixed(2) to round to 2 decimal places. parseFloat is much less strict with input and will pluck the first number it can find out of a string, as long as that string starts with a number, eg. parseFloat("123abc") would yield 123.
I built my answer from the accepted answer.
var regex = /^[1-9]\d*(((,\d{3}){1})?(\.\d{0,2})?)$/;
^[1-9] The number must start with 1-9
\d* The number can then have any number of any digits
(...)$ look at the next group from the end (...)$
(...)?(...)? Look for two groups optionally. The first is for the comma, the second is for the decimal.
(,\d{3}){1} Look for one occurance of a comma followed by exactly three digits
\.\d{0,2} Look for a decimal followed by zero, one, or two digits.
This regex works off of these rules:
Valid values are numbers 0-9, comma and decimal point.
If a customer enters more than one decimal point or more than one comma, the value is invalid and will not be accepted.
Examples of invalid input values
1.2.3
1,2,4
Examples of valid input values
1.23
1,000
3967.
23
1.2
999,999.99
An example can be seen here:
http://jsfiddle.net/rat141312/Jpxu6/1/
UPDATE
by changing the [1-9] in the regex to [0-9] any number less than 1 can also be validated. Example: 0.42, 007
/[1-9]\d*(?:\.\d{0,2})?/
[1-9] - must start with 1 to 9
\d* - any number of other digits
(?: )? - non capturing optional group
\. - a decimal point
\d{0,2} - 0 to 2 digits
does that work for you?
or maybe parseFloat:
var float = parseFloat( input );
let amount = document.querySelector('#amount'), preAmount = amount.value;
amount.addEventListener('input', function(){
if(isNaN(Number(amount.value))){
amount.value = preAmount;
return;
}
let numberAfterDecimal = amount.value.split(".")[1];
if(numberAfterDecimal && numberAfterDecimal.length > 3){
amount.value = Number(amount.value).toFixed(3);;
}
preAmount = amount.value;
})
<input type="text" id="amount">
For me its working fine for Indian currency in INR
var regex = /^[1-9]{0,2}(,{0,1})(\d{2},)*(\d{3})*(?:\.\d{0,2})$/;
var a = '1,111.11';
regex.test(a);
Now I use this:
let func = function (vStr) {
let v0 = Number(vStr);
let v1 = Number(v0.toFixed(2));
return v0 === v1;
};
Note that, NaN === NaN returns false. Maybe some substitution for '$' and ',' before parsing is needed, for other cases.
And there is a problem of precision for very large number, longer than 16 digits. As well as values of '0x3a', '68n' is considered valid.
Nowadays, <input> of type="number", with step='.01' may be more proper.

Categories