Detect round number in PHP?

How can I find out whether a float in PHP is a round number?

is_round(1.5); // false
is_round(1.0); // true
is_round(1.00000001); // false

Answers


Modification to Rob's code regarding sterofrog's comment. Code checks to ensure the value is also numeric.

function is_round($value) {
    return is_numeric($value) && intval($value) == $value;
}

function is_round( $value ) {
    return intval( $value ) == $value;
}

A much shorter version: !fmod($num,1) in PHP or this in JS: !($num % 1)

As a (more readable) function:

function is_round( $num ) {
  return !fmod($num, 1);
}

This works on the basis that any number that's not exactly 0 is falsey. You can use fmod($num,1) to get the decimals of a number; once you have those you can just ! them.


The function specified on this page by thierryreeuwijk should specify your needs.


if ($value = round($value))

Should work.


Need Your Help

php mail attachments with message

php phpmailer email-attachments

I have seen this is a common question but through searching I haven't found the answer I need. I have used PHP code to create a mailer with attachments that are located on my server.

Consuming webservice in excel and deploying as one file

web-services excel-vba excel-2007 vba excel

I would like to fetch some data into my Excel Spreadsheet (Excel 2007) from webservice, but I would like to deploy the spreadsheet as one file only (f.e. spreadsheet.xlsx - nothing more).