# JavaScript Regular Expression decimal type

Source: Internet
Author: User

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+\$/http://blog.csdn.net/xxd851116/article/details/4352011

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]+\$/ http://social.msdn.microsoft.com/Forums/en-US/1ffd9265-eafa-4897-b803-39194f35df5d/ 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);`

Explain:

^\$ 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 Keywords:
Related Article

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

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

## Alibaba Cloud Free Trial

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