Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex - valid float number

Tags:

I want user only input 0-9 and only once "."

 patt = /[^0-9(.{1})]/   1.2222 -> true  1.2.2  -> false (only once '.') 

help me , thank !

like image 419
Chameron Avatar asked Oct 15 '10 09:10

Chameron


People also ask

What type of numbers are represented by following regular expression 0 9 ]+ 0 9 ]+?

[0-9]+|[0-9]+). This regular expression matches an optional sign, that is either followed by zero or more digits followed by a dot and one or more digits (a floating point number with optional integer part), or that is followed by one or more digits (an integer).

What is a floating point numbers in PHP?

In PHP, the Float data type is used to set fractional values. A float is a number with a decimal point and can be extended to exponential form. Float is also called a floating-point number. Various ways to represent float values are 3.14, 4.75, 5.88E+20, etc.

Is float integer in PHP?

PHP Integers An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems, and between -9223372036854775808 and 9223372036854775807 in 64 bit systems. A value greater (or lower) than this, will be stored as float, because it exceeds the limit of an integer.

How can I check if a string is integer or float in PHP?

The is_float() function checks whether a variable is of type float or not. This function returns true (1) if the variable is of type float, otherwise it returns false.


2 Answers

this is what you're looking for

$re = "~        #delimiter     ^           # start of input     -?          # minus, optional     [0-9]+      # at least one digit     (           # begin group         \.      # a dot         [0-9]+  # at least one digit     )           # end of group     ?           # group is optional     $           # end of input ~xD"; 

this only accepts "123" or "123.456", not ".123" or "14e+15". If you need these forms as well, try is_numeric

like image 50
user187291 Avatar answered Sep 20 '22 13:09

user187291


/^-?(?:\d+|\d*\.\d+)$/ 

This matches normal floats e.g. 3.14, shorthands for decimal part only e.g. .5 and integers e.g. 9 as well as negative numbers.

like image 26
Core Xii Avatar answered Sep 19 '22 13:09

Core Xii