Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex for decimal number
Regex pattern · validation

Regex for decimal number

Regex for decimal number: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /^-?\d+(?:\.\d+)?$/ as a decimal number regex. It matches "3.14" and "-0.5", and rejects ".5" and "3.". Use ^-?(?:\d+\.?\d*|\.\d+)$ to also accept .5 and 3.

Last updated · Maintained by FreeAIToolz · How we test

/^-?\d+(?:\.\d+)?$/
  • 3.14matches
  • -0.5matches
  • 42matches
  • 100.00matches
  • .5no match
  • 3.no match
  • 1,000.50no match
  • abcno match
  • 1.2.3no match
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
^-?\d+optional minus and whole-number part
(?:\.\d+)?$optional dot followed by digits

Examples

InputResult
3.14✓ Matches
-0.5✓ Matches
42✓ Matches
100.00✓ Matches
.5✗ No match
3.✗ No match
1,000.50✗ No match
abc✗ No match
1.2.3✗ No match

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

Use ^-?(?:\d+\.?\d*|\.\d+)$ to also accept .5 and 3. Locales that use a comma as decimal separator need [.,].

When to use this pattern

Prices, measurements and coordinates entered as plain numbers.

Use it in your language

JavaScript

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

Python

import re
pattern = re.compile(r'^-?\d+(?:\.\d+)?$')
bool(pattern.search(value))

PHP

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

Java

Pattern pattern = Pattern.compile("^-?\\d+(?:\\.\\d+)?$");
boolean ok = pattern.matcher(value).find();

Go

re := regexp.MustCompile(`^-?\d+(?:\.\d+)?$`)
ok := re.MatchString(value)

More regex patterns

Frequently asked questions

What is the regex for decimal number?
/^-?\d+(?:\.\d+)?$/. Use ^-?(?:\d+\.?\d*|\.\d+)$ to also accept .5 and 3. Locales that use a comma as decimal separator need [.,].
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
Why does the pattern start with ^ and end with $?
They anchor the match to the whole string, so "abc3.14xyz" cannot pass just because it contains a valid part. To search for matches inside longer text, remove ^ and $ (use \b where word boundaries help) and add the g flag.