Regular expression to enforce 2 digits after decimal point - javascript

I need to validate a numeric string with JavaScript, to ensure the number has exactly two decimal places.
The validation will pass only if
the number has precisely two decimal places
there is at least one digit before the decimal point. (could be zero)
the number before the decimal point can not begin with more than one zero.
Valid numbers:
0.01
0.12
111.23
1234.56
012345.67
123.00
0.00
Invalid numbers:
.12
1.1
0.0
00.00
1234.
1234.567
1234
00123.45
abcd.12
12a4.56
1234.5A
I have tried the regular expression [0-9][\.][0-9][0-9]$, but it allows letters before decimal point like 12a4.56.

. matches any character, it does not do what you think it does. You have to escape it. Also, you have two more errors; try
^[0-9]+\.[0-9][0-9]$
instead, or even better, use \d for decimal digits:
^\d+\.\d\d$

This covers all requirements:
^(0|0?[1-9]\d*)\.\d\d$
the number has precisely two decimal places
Trivially satisfied due to the non-optional \.\d\d$
The other two conditions can be restated as follows:
The number before the decimal points is either a zero
or a number with exactly one zero, then a number that does not start with zero
This is covered in these two cases:
0
0?[1-9]\d*

You don't need regular expressions for this.
JavaScript has a function toFixed() that will do what you need.
var fixedtotwodecimals = floatvalue.toFixed(2);

i used this
^[1-9][1-9]*[.]?[1-9]{0,2}$
0 not accept
123.12 accept but 123.123 not accept
1 accept
12213123 accept
sdfsf not accept
15.12 accept
15#12 not accept
15&12 not accept

var values='0.12';
document.write(values.match(/\d+[.]+\d+\d/));
change value as you want and check it

Here it is:
^(0[.]+\d{2})|^[1-9]\d+[.]+\d{2}$

Try This Code
pattern="[0-9]*(\.?[0-9]{1,2}$)?"
1 Valid
1.1 Valid
1.12 Valid
1.123 not Valid
only number Valid
pattern="[0-9]*(.?[0-9]{2}$)?"
1 Valid
1.1 not Valid
1.12 Valid
1.123 not Valid
only number Valid

Related

Javascript regex positive less than 10000 than can be decimal

I need a regex for a number than can be decimal and less than 10000 with max 2 digits after decimal.
I tried
/^([0-9]{1,4})+(\.[0-9]{0,2})$/
but it returns true for 44555.54 for example.
In your regex you are using + which is using for one or more repetition and which leads to match any length of digit and make decimal part non-greedy(using?) to make it optional.
^[0-9]{1,4}(\.[0-9]{0,2})?$
or using \d for digit character class.
^\d{1,4}(\.\d{0,2})?$

Regular Expression: Help Matching a number less than 24

so I'm making this regular expression to verify some text boxes on a website that I'm designing for an internship.
The problem is that I'm not so keen on regular expressions, and I'm close to having a working one that matches a number between 0-24 and no more than two decimal places.
This is what I have so far. The pattern is also matching any string; such as, "a" or "az".
var pattern = "^([0-9]{0,2}?.?[0-9]{0,2}|1[0-9].?[0-9]{0,2}|2[0-4].?[0-9]{0,2})$";
To get a number between 0 and 24 (24 excluded) with optional up to two decimal places:
^(\d|1\d|2[0-3])(\.\d{1,2})?$
The decimal part:
\. - match the decimal dot
\d{1,2} - one or two digits
()? - makes it optional
The whole part:
\d - numbers 0-9
1\d - numbers 10-19
2[0-3] - numbers 20-23
(x|y|z) - one of x, y or z
As for the "why is my version matching things like "a" and "az" part" - it's a little complex, but it basically boils down to you using dots (like .?). In regex, a dot means "any one character". To make it match a literal dot, you need to escape it with a slash just like I did.
Minor remark: If you want optional leading zero for single digit numbers, replace 1\d with [01]\d. If you want mandatory leading zero for single digit numbers, replace \d|1\d with [01]\d. If you don't want leading zeroes, leave it as it is.
Assuming you do not want 05 or 5.50
^((?:[0-9]|1[0-9]|2[0-3])(?:\.(?:[1-9]|[0-9][1-9]))?)$
You can try it here
The following is a quick attempt to match a floating point number from 0 to 24.99 with up to two non-zero digits
^(([0-9])|([01][0-9])|(2[0-4]))(\.[0-9]{1,2})?$
I think it might be easier to use math to do this though...
You can see the explanation of the entire regex as well as test it out here. I have also added a few test cases.
^(\d|[01]\d|2[0-3])(\.\d{1,2})?$
Test cases:
Valid:
22
1.29
2.99
9.99
13.24
17.38
20.01
02.15
15.35
23.56
1.1
Invalid:
24.29
235.215
21.256
To get a integer number between 1 and 23: ^([1-9]|1[0-9]|2[0-3])$

Regex for number with decimals and thousand separator

I need regex to validate a number that could contain thousand separators or decimals using javascript.
Max value being 9,999,999.99
Min value 0.01
Other valid values:
11,111
11.1
1,111.11
INVALID values:
1111
1111,11
,111
111,
I've searched all over with no joy.
/^\d{1,3}(,\d{3})*(\.\d+)?$/
About the minimum and maximum values... Well, I wouldn't do it with a regex, but you can add lookaheads at the beginning:
/^(?!0+\.00)(?=.{1,9}(\.|$))\d{1,3}(,\d{3})*(\.\d+)?$/
Note: this allows 0,999.00, so you may want to change it to:
/^(?!0+\.00)(?=.{1,9}(\.|$))(?!0(?!\.))\d{1,3}(,\d{3})*(\.\d+)?$/
which would not allow a leading 0.
Edit:
Tests: http://jsfiddle.net/pKsYq/2/
((\d){1,3})+([,][\d]{3})*([.](\d)*)?
It worked on a few, but I'm still learning regex as well.
The logic should be 1-3 digits 0-1 times, 1 comma followed by 3 digits any number of times, and a single . followed by any number of digits 0-1 times
First, I want to point out that if you own the form the data is coming from, the best way to restrict the input is to use the proper form elements (aka, number field)
<input type="number" name="size" min="0.01" max="9,999,999.99" step="0.01">
Whether "," can be entered will be based on the browser, but the browser will always give you the value as an actual number. (Remember that all form data must be validated/sanitized server side as well. Never trust the client)
Second, I'd like to expand on the other answers to a more robust (platform independent)/modifiable regex.
You should surround the regex with ^ and $ to make sure you are matching against the whole number, not just a subset of it. ex ^<my_regex>$
The right side of the decimal is optional, so we can put it in an optional group (<regex>)?
Matching a literal period and than any chain of numbers is simply \.\d+
If you want to insist the last number after the decimal isn't a 0, you can use [1-9] for "a non-zero number" so \.\d+[1-9]
For the left side of the decimal, the leading number will be non-zero, or the number is zero. So ([1-9]<rest-of-number-regex>|0)
The first group of numbers will be 1-3 digits so [1-9]\d{0,2}
After that, we have to add digits in 3s so (,\d{3})*
Remember ? means optional, so to make the , optional is just (,?\d{3})*
Putting it all together
^([1-9]\d{0,2}(,?\d{3})*|0)(\.\d+[1-9])?$
Tezra's formula fails for '1.' or '1.0'. For my purposes, I allow leading and trailing zeros, as well as a leading + or - sign, like so:
^[-+]?((\d{1,3}(,\d{3})*)|(\d*))(\.|\.\d*)?$
In a recent project we needed to alter this version in order to meet international requirements.
This is what we used: ^-?(\d{1,3}(?<tt>\.|\,| ))((\d{3}\k<tt>)*(\d{3}(?!\k<tt>)[\.|\,]))?\d*$
Creating a named group (?<tt>\.|\,| ) allowed us to use the negative look ahead (?!\k<tt>)[\.|\,]) later to ensure the thousands separator and the decimal point are in fact different.
I have used below regrex for following retrictions -
^(?!0|\.00)[0-9]+(,\d{3})*(.[0-9]{0,2})$
Not allow 0 and .00.
','(thousand seperator) after 3 digits.
'.' (decimal upto 2 decimal places).

round 2 decimals syntax from from input using jQuery

I have a simple conversion form from kg to lbs.
html
<input type="text" id="kg" name="kg">
<input type="text" id="lbs" name="lbs">
I have it setup so that the lbs box updates while you type in the kg box with this code.
jQuery
$("#kg").keyup(function(){
$('#lbs').val($('#kg').val()*2.20462);
});
How do I get the lbs value to round to 2 decimals places? I am sure it is something fairly simple but all the examples I found online are for if the number is stored in a variable.
Use toFixed
var string = yourNumber.toFixed(2);
use toFixed:
$('#lbs').val(($('#kg').val()*2.20462).toFixed(2));
number.toFixed( [digits] )
Parameter
digits The number of digits to appear after the decimal point; this
may be a value between 0 and 20, inclusive, and implementations may
optionally support a larger range of values. If this argument is
omitted, it is treated as 0.
Returns
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place. The
number is rounded if necessary, and the fractional part is padded with
zeros if necessary so that it has the specified length. If number is
greater than 1e+21, this method simply calls Number.toString() and
returns a string in exponential notation.
also this
(10.8).toFixed(2); // 10.80
var num = 2.4;
alert(num.toFixed(2)); // 2.40
Formatting a number with exactly two decimals in JavaScript

Regex which allows 3 digit before precision and 2 digits after precision

I have written a Regex which will take only integers but I need to rewrite this regex to only allow 3 digit before precision and 2 digits after precision
How to do that?
If it must always have 3 digits, a decimal point, and 2 digits, e.g., 412.88, then:
/^\d{3}\.\d{2}$/
If it can be up to 3 digits before and up to 2 after (possibly no decimal point at all) then maybe something like:
/^\d{1,3}(\.\d{1,2})?$/
In c#
#"^\d{3}\.\d{2}$"
//in c# we need to use verbatim string `#""` to treat escape sequences as normal literals instead of giving it a special meaning..
In javascript
/^\d{3}\.\d{2}$/

Categories