How to get whole and decimal part of a number?

The floor() method doesn't work for negative numbers. This works every time:

$num = 5.7;
$whole = (int) $num;  // 5
$frac  = $num - $whole;  // .7

...also works for negatives (same code, different number):

$num = -5.7;
$whole = (int) $num;  // -5
$frac  = $num - $whole;  // -.7

This code will split it up for you:

list($whole, $decimal) = explode('.', $your_number);

where $whole is the whole number and $decimal will have the digits after the decimal point.


Just to be different :)

list($whole, $decimal) = sscanf(1.5, '%d.%d');

CodePad.

As an added benefit, it will only split where both sides consist of digits.


$n = 1.25;
$whole = floor($n);      // 1
$fraction = $n - $whole; // .25

Then compare against 1/4, 1/2, 3/4, etc.


In cases of negative numbers, use this:

function NumberBreakdown($number, $returnUnsigned = false)
{
  $negative = 1;
  if ($number < 0)
  {
    $negative = -1;
    $number *= -1;
  }

  if ($returnUnsigned){
    return array(
      floor($number),
      ($number - floor($number))
    );
  }

  return array(
    floor($number) * $negative,
    ($number - floor($number)) * $negative
  );
}

The $returnUnsigned stops it from making -1.25 in to -1 & -0.25

Tags:

Php

Math