[php] Check if number is decimal

I need to check in PHP if user entered a decimal number (US way, with decimal point: X.XXX)

Any reliable way to do this?

This question is related to php function decimal

The answer is


You can get most of what you want from is_float, but if you really need to know whether it has a decimal in it, your function above isn't terribly far (albeit the wrong language):

function is_decimal( $val )
{
    return is_numeric( $val ) && floor( $val ) != $val;
}

the easy way to find either posted value is integer and float so this will help you

$postedValue = $this->input->post('value');
if(is_numeric( $postedValue ) && floor( $postedValue ))
{
    echo 'success';
}
else
{
   echo 'unsuccess';
}

if you give 10 or 10.5 or 10.0 the result will be success if you define any character or specail character without dot it will give unsuccess


   // if numeric 

if (is_numeric($field)) {
        $whole = floor($field);
        $fraction = $field - $whole;

        // if decimal            
        if ($fraction > 0)
            // do sth
        else
        // if integer
            // do sth 
}
else

   // if non-numeric
   // do sth

The function you posted is just not PHP.

Have a look at is_float [docs].

Edit: I missed the "user entered value" part. In this case you can actually use a regular expression:

^\d+\.\d+$

Maybe try looking into this as well

!is_int()


If all you need to know is whether a decimal point exists in a variable then this will get the job done...

function containsDecimal( $value ) {
    if ( strpos( $value, "." ) !== false ) {
        return true;
    }
    return false;
}

This isn't a very elegant solution but it works with strings and floats.

Make sure to use !== and not != in the strpos test or you will get incorrect results.


is_numeric returns true for decimals and integers. So if your user lazily enters 1 instead of 1.00 it will still return true:

echo is_numeric(1); // true
echo is_numeric(1.00); // true

You may wish to convert the integer to a decimal with PHP, or let your database do it for you.


another way to solve this: preg_match('/^\d+\.\d+$/',$number); :)


I was passed a string, and wanted to know if it was a decimal or not. I ended up with this:

function isDecimal($value) 
{
     return ((float) $value !== floor($value));
}

I ran a bunch of test including decimals and non-decimals on both sides of zero, and it seemed to work.


This is a more tolerate way to handle this with user input. This regex will match both "100" or "100.1" but doesn't allow for negative numbers.

/^(\d+)(\.\d+)?$/

A total cludge.. but hey it works !

$numpart = explode(".", $sumnum); 

if ((exists($numpart[1]) && ($numpart[1] > 0 )){
//    it's a decimal that is greater than zero
} else {
// its not a decimal, or the decimal is zero
}

Simplest solution is

if(is_float(2.3)){

 echo 'true';

}

If you are working with form validation. Then in this case form send string. I used following code to check either form input is a decimal number or not. I hope this will work for you too.

function is_decimal($input = '') {

    $alphabets = str_split($input);
    $find = array('0','1','2','3','4','5','6','7','8','9','.'); // Please note: All intiger numbers are decimal. If you want to check numbers without point "." then you can remove '.' from array. 

    foreach ($alphabets as $key => $alphabet) {
        if (!in_array($alphabet, $find)) {
            return false;
        }
    }

    // Check if user has enter "." point more then once.
    if (substr_count($input, ".") > 1) {
        return false;
    }

    return true;
}

$lat = '-25.3654';

if(preg_match('/./',$lat)) {
    echo "\nYes its a decimal value\n";
}
else{
    echo 'No its not a decimal value';
}

if you want "10.00" to return true check Night Owl's answer

If you want to know if the decimals has a value you can use this answer.

Works with all kind of types (int, float, string)

if(fmod($val, 1) !== 0.00){
    // your code if its decimals has a value
} else {
    // your code if the decimals are .00, or is an integer
}

Examples:

(fmod(1.00,    1) !== 0.00)    // returns false
(fmod(2,       1) !== 0.00)    // returns false
(fmod(3.01,    1) !== 0.00)    // returns true
(fmod(4.33333, 1) !== 0.00)    // returns true
(fmod(5.00000, 1) !== 0.00)    // returns false
(fmod('6.50',  1) !== 0.00)    // returns true

Explanation:

fmod returns the floating point remainder (modulo) of the division of the arguments, (hence the (!== 0.00))

Modulus operator - why not use the modulus operator? E.g. ($val % 1 != 0)

From the PHP docs:

Operands of modulus are converted to integers (by stripping the decimal part) before processing.

Which will effectively destroys the op purpose, in other languages like javascript you can use the modulus operator


i use this:

function is_decimal ($price){
  $value= trim($price); // trim space keys
  $value= is_numeric($value); // validate numeric and numeric string, e.g., 12.00, 1e00, 123; but not -123
  $value= preg_match('/^\d$/', $value); // only allow any digit e.g., 0,1,2,3,4,5,6,7,8,9. This will eliminate the numeric string, e.g., 1e00
  $value= round($value, 2); // to a specified number of decimal places.e.g., 1.12345=> 1.12

  return $value;
}

function is_decimal_value( $a ) {
    $d=0; $i=0;
    $b= str_split(trim($a.""));
    foreach ( $b as $c ) {
        if ( $i==0 && strpos($c,"-") ) continue;
        $i++;
        if ( is_numeric($c) ) continue;
        if ( stripos($c,".") === 0 ) {
            $d++;
            if ( $d > 1 ) return FALSE;
            else continue;
        } else
        return FALSE;
    }
    return TRUE;
}

Known Issues with the above function:

1) Does not support "scientific notation" (1.23E-123), fiscal (leading $ or other) or "Trailing f" (C++ style floats) or "trailing currency" (USD, GBP etc)

2) False positive on string filenames that match a decimal: Please note that for example "10.0" as a filename cannot be distinguished from the decimal, so if you are attempting to detect a type from a string alone, and a filename matches a decimal name and has no path included, it will be impossible to discern.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to decimal

Java and unlimited decimal places? What are the parameters for the number Pipe - Angular 2 Limit to 2 decimal places with a simple pipe C++ - Decimal to binary converting Using Math.round to round to one decimal place? String to decimal conversion: dot separation instead of comma Python: Remove division decimal Converting Decimal to Binary Java Check if decimal value is null Remove useless zero digits from decimals in PHP