Problem
How can I retrieve the “1” and “.25” components of a number like 1.25?
I’m trying to figure out if the decimal component is.0,.25,.5, or.75.
Asked by StackOverflowNewbie
Solution #1
$n = 1.25;
$whole = floor($n); // 1
$fraction = $n - $whole; // .25
Then compare it to 1/4, 1/2, 3/4, and so on.
Use this when dealing with negative numbers:
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
);
}
$returnUnsigned prevents it from converting -1.25 to -1 & -0.25.
Answered by Brad Christie
Solution #2
This code will help you break it up:
list($whole, $decimal) = explode('.', $your_number);
where $decimal will have the digits after the decimal point and $whole will be the complete number.
Answered by shelhamer
Solution #3
For negative values, the floor() method is ineffective. This method is always effective:
$num = 5.7;
$whole = (int) $num; // 5
$frac = $num - $whole; // .7
…also works for negatives (different number, same code):
$num = -5.7;
$whole = (int) $num; // -5
$frac = $num - $whole; // -.7
Answered by thedude
Solution #4
Just to stand out:)
list($whole, $decimal) = sscanf(1.5, '%d.%d');
CodePad.
It will also only divide where both sides are made up of digits as an added bonus.
Answered by alex
Solution #5
a short distance (use floor and fmod)
$var = "1.25";
$whole = floor($var); // 1
$decimal = fmod($var, 1); //0.25
then compare $decimal to 0 (decimal),.25 (decimal),.5 (decimal), or.75 (decimal).
Answered by mpalencia
Post is based on https://stackoverflow.com/questions/6619377/how-to-get-whole-and-decimal-part-of-a-number