Mr.M
Mr.M

Reputation: 684

How to validate to accept only float values in php

I am looking to validate a field using php. The value to be entered in that field should be a float value. None other can be accepted. Not even integer. It should accept values like 5.2 or 4.1 and so on. Integers like 3 or 56 or 123 etc will also not be accepted. Hope it is clear.

Thanks in advance

Upvotes: 0

Views: 1493

Answers (3)

Amit Garg
Amit Garg

Reputation: 3907

$x='1.23';
if(preg_match('/^(\d)*\.(\d)+$/',$x)){
    echo 'yes';
}else{
    echo 'No';
}

You can check with regex because the value you receive from text field will be string.

Upvotes: 0

Andrew Mackrodt
Andrew Mackrodt

Reputation: 1826

is_float will fail with strings (e.g. get or post submissions). To check if a value is numeric use is_numeric. To check for a float value, cast to an integer and check for equality:

function is_float_value($value) {
    return is_numeric($value) && ('' . (int)$value) !== "$value";
}

echo is_float_value("53.1") ? "yes\n" : "no\n"; // yes
echo is_float_value(53.1)   ? "yes\n" : "no\n"; // yes
echo is_float_value("0.0")  ? "yes\n" : "no\n"; // yes
echo is_float_value(0.0)    ? "yes\n" : "no\n"; // no - internally represented as 0
echo is_float_value("53")   ? "yes\n" : "no\n"; // no
echo is_float_value(53)     ? "yes\n" : "no\n"; // no

Upvotes: 1

Make use of the is_float in PHP.

<?php
if (is_float(53)) {
    echo "is float\n";
} else {
    echo "is not float\n";  //<---- This will be printed !
}

Demo

Upvotes: 1

Related Questions