How do I know if a decimal number is even or odd? [duplicate]

1

You have several questions related to this question, but these are always integers.

For example:

<?php

function evenOdd($number){
    $conta = $number / 2;
    $resto = $number % 2;

    if($resto == 0.0)
        echo $conta.' - Par';
    else
        echo $conta.' - Ímpar';
}

evenOdd(11.8); 
echo ' | ';
evenOdd(10.8);
echo ' | ';
evenOdd(5.075);
echo ' | ';
evenOdd(4.39);

What's the gist of whether it's even or odd?

    
asked by anonymous 09.11.2016 / 15:03

2 answers

1

As already explained by @jbueno, only integers can be classified as even or odd.

For a number to be even, you need:

  • Be an integer multiple of two, that is, it can be written in the form 2x;
  • Be divisible by 2;
  • Be surrounded by odd numbers;
  • Can be divided into two groups with an equal integer number;
  • Compatible with all rules of sums / subtractions and even and odd numbered products.

If not, do not follow the rules above, so it is Odd.

In practice, to know if a number is PAR, just check if the remainder of the division by 2 equals 0 (zero)

function ePar($numero){
    if($numero % 2 == 0){ // se o resto da divisão do número por 2 = 0
       return true; // é par
    }else{
       return false; // não é par
    }
}

Usage:

var_dump(ePar(43));
var_dump(ePar(44));
var_dump(ePar(46.7));

Output:

  

bool (false)

     

bool (true)

     

number entered is not integer

    
09.11.2016 / 16:13
3

This is more a question of math than of PHP itself. Only integers can be classified as even or odd.

Answering your question.

  

What's the gist of whether it's even or odd?

Just check the module (remainder) of the division by 2, if the rest is 0 the number is even, if it is 1 the number is odd. Therefore, all numbers ending in 1, 3, 5, 7, and 9 are odd, those ending in 0, 2, 4, 6, and 8 are even.

    
09.11.2016 / 15:13