Home > database >  Regular expression for positive number with 2 decimals used for displaying money
Regular expression for positive number with 2 decimals used for displaying money

Time:10-31

I am looking for a regular expression for displaying numbers with 2 decimals for displaying money of various currencies in the world. This regex should only allow 1 dot or comma as a decimal separator. And only allow positive numbers and the numbers can't begin with a 0.

Goals:

  • Both dot and comma can be used as a decimal separator
  • The decimal separator can only be once in a number
  • Numbers can't begin with a zero
  • Only positive numbers allowed

CodePudding user response:

Solution

My solution for this dilemma is the following: ^[1-9]\d*([\,\.]\d{2})?$

Explanation

^[1-9] tells regex that a number needs to start with 1 to 9

\d* tells regex that the next thing needs to be a number between 0 to 9 and can be matched 0 or more times

([\,\.]\d{2})?$ tells regex that there can be a dot or a comma and that there must be exactly 2 numbers after it. The question mark makes it also optional so either 100 or 100,00 or 100.00 is okay. So positive natural numbers or positive 2 decimal numbers

This regex could also be easily edited to support negative and positive numbers with or without 2 decimals.

Verification

https://regex101.com/r/w6WXTi/2

  • Related