JavaScript Regular Expression decimal type

Source: Internet
Author: User

If you want to read and understand it, you can read it a bit. If you only need the results, skip to the end of this article.

There was a need to match the decimal type with a JavaScript regular expression, and then the previous writing was not fully recognized.

Later on the internet to find a lot, even some foreigners, including some of the Pure English Forum, found all is wrong, are not comprehensive.

Common errors:

1. /^-?\d+\.\d+$/

A casual look will know, if the front with + is wrong, if there is no decimal point is wrong, if 00.123 also good newspaper and so on

2./^[0-9]*[.] [0-9]+$/ Regular-expression-for-a-float-in-javascript?forum=jscript

Almost like the last one.

3. /^\d*+ (\.\d+)? $/ The same page as the previous one

There seems to be a lot of levels, such as the decimal point and after the decimal point can have no (that is, integers can, not just decimal fraction)

But before the decimal point, 00.123 is also possible.

No way.

4. /^[+-]?\d+ (\.\d+) $/

is also better, such as considering the positive and negative signs, and so on, but the same decimal point before 00.123 is also possible

Don't look for more, that's probably the case.


Here is a notation I have tested several times:

var regExp =/^[+-]? (0| ([1-9]\d*)) (\.\d+)? $/g;var B = regexp.test (a); alert (b);


^$ matches the end of the string, respectively

[+-]? Indicates that the beginning of a string can have a + or-or no symbol, and there can be only one

0| [1-9]\d* This is the integer part before the decimal point, which indicates that it can be either (a 0) or (for a first-digit not 0 integer, but the first bit can be 0 later)

(\.\d+)? Refers to the decimal point and the back part of the decimal point, not appearing or appearing once

G all matches, (as if not required)

Therefore, the perfect match for the decimal type.

JavaScript Regular Expression decimal type

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.