Regex for decimal number

Use /^-?\d+(?:\.\d+)?$/ to check that a whole string is a valid for decimal number. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^-?\d+(?:\.\d+)?$/
Open in Regex Tester
InputResult
42✓ Match
-3.14✓ Match
0.5✓ Match
.5✗ No match
1.✗ No match
1,000✗ No match
abc✗ No match
+1✗ No match

How the pattern works

PartMeaning
-?Optional minus sign
\d+Whole part
(?:\.\d+)?Optional dot and decimal digits

Code examples

JavaScript

const re = /^-?\d+(?:\.\d+)?$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'-?\d+(?:\.\d+)?', value))

PHP

preg_match('/^-?\d+(?:\.\d+)?$/', $value) === 1;

Notes and limitations

Allow .5 by changing \d+ to \d* in the whole part (and make sure the string isn’t empty).

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for decimal number?
/^-?\d+(?:\.\d+)?$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: 42, -3.14, 0.5. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.