39

I want a regex in JavaScript for validating decimal numbers.

It should allow only up to two decimal places. For example, it should allow 10.89 but not 10.899.

It should also allow only one period (.). For example, it should allow 10.89 but not 10.8.9.

2

12 Answers 12

54

Try the following expression: ^\d+\.\d{0,2}$ If you want the decimal places to be optional, you can use the following: ^\d+(\.\d{1,2})?$

EDIT: To test a string match in Javascript use the following snippet:

var regexp = /^\d+\.\d{0,2}$/;

// returns true
regexp.test('10.5')
Sign up to request clarification or add additional context in comments.

2 Comments

@micha, sorry fixed the typo in my first regexp
Use var regexp = /^\d+\.?\d{0,2}$/; if you want to have a optional commaseparator.
54

Positive decimals only

/^\d+(\.\d{1,2})?$/

Negative or positive decimals

/^-?\d+(\.\d{1,2})?$/

Demo

var regexp = /^\d+(\.\d{1,2})?$/;

console.log("POSITIVE ONLY");
console.log("'.74' returns " + regexp.test('.74'));
console.log("'7' returns " + regexp.test('7'));
console.log("'-4' returns " + regexp.test('-4'));
console.log("'10.5' returns " + regexp.test('10.5'));
console.log("'115.25' returns " + regexp.test('115.25'));
console.log("'-120.56' returns " + regexp.test('-120.56'));
console.log("'1535.803' returns " + regexp.test('1535.803'));
console.log("'153.14.5' returns " + regexp.test('153.14.5'));
console.log("'415351108140' returns " + regexp.test('415351108140'));
console.log("'415351108140.55' returns " + regexp.test('415351108140.55'));
console.log("'415351108140.556' returns " + regexp.test('415351108140.556'));

regexp = /^-?\d+(\.\d{1,2})?$/;

console.log("\n");
console.log("POSITIVE OR NEGATIVE");
console.log("'.74' returns " + regexp.test('.74'));
console.log("'7' returns " + regexp.test('7'));
console.log("'-4' returns " + regexp.test('-4'));
console.log("'10.5' returns " + regexp.test('10.5'));
console.log("'115.25' returns " + regexp.test('115.25'));
console.log("'-120.56' returns " + regexp.test('-120.56'));
console.log("...");


Explanation

  1. / / : the beginning and end of the expression
  2. ^ : whatever follows should be at the beginning of the string you're testing
  3. \d+ : there should be at least one digit
  4. ( )? : this part is optional
  5. \. : here goes a dot
  6. \d{1,2} : there should be between one and two digits here
  7. $ : whatever precedes this should be at the end of the string you're testing

If you also want to support negative decimals, you just need to add -? right after the ^, which means that an optional minus sign is allowed there as well.


Tip

You can use regexr.com or regex101.com for testing regular expressions directly in the browser!

3 Comments

How would I extend this to accept negative numbers as well?
@KylianMbappe : I just updated my answer to add support for negative decimals
Here is a better solution for me /^\d{0,13}(\.\d{1,2}0*)?$/.test(yourNumber) to allow 10.1200 that you can remove using Number(yourNumber.toFixed(2)) but only when the condition is correct !
43
^\d+(\.\d{1,2})?$

will allow:

  1. 244
  2. 10.89
  3. 9.5

will disallow:

  1. 10.895
  2. 10.
  3. 10.8.9

2 Comments

@ShardaprasadSoni see my post for an example
If I type 0000.100 which will be invalid decimal what the regExp should be?
4

Numbers with at most 2 decimal places:

/^\d+(?:\.\d{1,2})?$/

This should work fine. Please try out :)

1 Comment

How can I set the max decimals with a variable? Thanks
4

I found that I could use

^\d+(\.\d+)?$

for more than two decimal places.

Comments

4

Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of custom filter of input of an float number with decimal pointer and limitation to 2 digit after decimal pointer:

<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Input Key Filter Test</title>
	<meta name="author" content="Andrej Hristoliubov [email protected]">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	
	<!-- For compatibility of IE browser with audio element in the beep() function.
	https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->
	<meta http-equiv="X-UA-Compatible" content="IE=9"/>
	
	<link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">		
	<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>
	<script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>
	
</head>
<body>
	<h1>Float field</h1>
<input id="Float" 
	onchange="javascript: onChangeFloat(this)"
	onblur="inputKeyFilter.isNaN(parseFloat(this.value), this);"
/>
<script>
	function CreateFloatFilterCustom(elementID, onChange, onblur){
		try{
			inputKeyFilter.Create(elementID
				, onChange
				, function(elementInput, value){//customFilter
					if(value.match(/^(-?\d*)((\.(\d{0,2})?)?)$/i) == null){
						inputKeyFilter.TextAdd(isRussian() ?
								"Допустимый формат: -[0...9].[0...9] или -[0...9]e-[0...9]. Например: -12.34 1234"
								: "Acceptable formats: -[0...9].[0...9] or -[0...9]e-[0...9]. Examples: -12.34 1234"
							, elementInput);
						return false;
					}
					return true;
				}
				, onblur
			)
		} catch(e) {
			consoleError("Create float filter failed. " + e);
		}
	}
	
	CreateFloatFilterCustom("Float");
	
	function onChangeFloat(input){
		inputKeyFilter.RemoveMyTooltip();
		var elementNewFloat = document.getElementById("NewFloat");
		var float = parseFloat(input.value);
		if(inputKeyFilter.isNaN(float, input)){
			elementNewFloat.innerHTML = "";
			return;
		}
		elementNewFloat.innerHTML = float;
	}
</script>
 New float: <span id="NewFloat"></span>
</body>
</html>

Also see my page example of the input key filter

2 Comments

Can we restrict before decimal to be only 6 digits ?
replace from /^(-?\d*)((\.(\d{0,2})?)?)$/i to /^(-?\d{0,6})((\.(\d*)?)?)$/i
3

Try a regular expression like this:

(?=[^\0])(?=^([0-9]+){0,1}(\.[0-9]{1,2}){0,1}$)

Allowed: 1, 10.8, 10.89, .89, 0.89, 1000

Not Allowed: 20. , 50.89.9, 12.999, ., Null character Note this works for positive numbers

Comments

3

Since you asked for decimal numbers validation, for completeness' sake, I'd use a regex that doesn't allow strings like 06.05.

^((0(\.\d{1,2})?)|([1-9]\d*(\.\d{1,2})?))$

Slightly more complicated, but returns false in that case.

Edit:

^-?((0(\.\d{1,2})?)|([1-9]\d*(\.\d{1,2})?))$

if you want negative numbers as well.

2 Comments

This actually does not handle decimals in range [0, 1)
It does, test here regex101.com. Particularly, this first half does (0(\.\d{1,2})?). Or at least it does up to 2 decimal places like OP asked.
0

as compared from the answer gven by mic... it doesnt validate anything in some of the platforms which i work upon... to be precise it doesnt actually work out in Dream Viewer..

hereby.. i re-write it again..which will work on any platform.. "^[0-9]+(.[0-9]{1,2})?$".. thnkss..

Comments

0
 function CheckValidAmount() {
        var amounttext = document.getElementById('txtRemittanceNumber').value;            
        if (!(/^[-+]?\d*\.?\d*$/.test(amounttext))){
            alert('Please enter only numbers into amount textbox.')
            document.getElementById('txtRemittanceNumber').value = "10.00";
        }
    }

This is the function which will take decimal number with any number of decimal places and without any decimal places.

Thanks ... :)

2 Comments

Can you post the code as text rather than an image?
for what did you used var amount = parseFloat(amounttext); if later you are using test(amounttext) and amount is not used anywhere?
0

The schema for passing the value in as a string. The regex will validate a string of at least one digit, possibly followed by a period and exactly two digits:

{
    "type": "string",
    "pattern": "^[0-9]+(\\.[0-9]{2})?$"
}

The schema below is equivalent, except that it also allows empty strings:

{
    "type": "string",
    "pattern": "^$|^[0-9]+(\\.[0-9]{2})?$"
}

Comments

-3

Does this work?

[0-9]{2}.[0-9]{2}

1 Comment

. stands for any character | [0-9] is the same as \d

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.