how to check valid decimal point number with Regex?

橙三吉。 提交于 2019-12-24 00:53:27

问题


how can i check number is valid with below string.

last 2 digit may content decimal value or may not.

below are the code which i have already tried with preg_match but couldn't get any success

$newPrice = "2,264.00"; or //  $newPrice = "264.00"; 

 if (!preg_match('/^[+-][0-9]+(\,[0-9]+)?%?$/', $newPrice))
{                
    echo "not valid";
 }else{                    
       echo "valid";
}
exit();

above both price is correct as per allowed format.


回答1:


The regex has 3 parts;

[0-9]{1,3}     1-3 digits
(,[0-9]{3})*   An optional repeated part of a comma + 3 digits
(\.[0-9]{2})?  An optional part of a decimal dot and 2 digits

This can be written as;

/^[0-9]{1,3}(,[0-9]{3})*(\.[0-9]{2})?$/



回答2:


try this

^[+-]?[\d\,]+\.?\d+?

this will match values like :

222,222,264.00
+2,424,24.34
-264
264.00

demo




回答3:


Use this regex:

[0-9,]+(?:\.[0-9]*)?

Debuggex Demo



来源:https://stackoverflow.com/questions/22396654/how-to-check-valid-decimal-point-number-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!