Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple regular expression for a decimal with a precision of 2

Tags:

regex

What is the regular expression for a decimal with a precision of 2?

Valid examples:

123.12 2 56754 92929292929292.12 0.21 3.1 

Invalid examples:

12.1232 2.23332 e666.76 

The decimal point may be optional, and integers may also be included.

like image 587
user39221 Avatar asked Nov 21 '08 07:11

user39221


People also ask

What is 2 digit precision?

Price precision determines the fixed number of decimal places to which a calculated price is rounded. Suppose precision is set at 2 digits. If the value of the third digit to the right of the decimal is less than 5, the hundredth position (second to the right of the decimal) remains unchanged.

How do you express 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do you make a float to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you write decimals in regular expressions?

A better regex would be /^\d*\.?\ d+$/ which would force a digit after a decimal point.


1 Answers

Valid regex tokens vary by implementation. A generic form is:

[0-9]+(\.[0-9][0-9]?)? 

More compact:

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

Both assume that both have at least one digit before and one after the decimal place.

To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):

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

To match numbers without a leading digit before the decimal (.12) and whole numbers having a trailing period (12.) while excluding input of a single period (.), try the following:

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

Added

Wrapped the fractional portion in ()? to make it optional. Be aware that this excludes forms such as 12. Including that would be more like ^\d+\\.?\d{0,2}$.

Added

Use ^\d{1,6}(\.\d{1,2})?$ to stop repetition and give a restriction to whole part of the decimal value.

like image 190
DocMax Avatar answered Oct 03 '22 05:10

DocMax