Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get whole and decimal part of a number?

Tags:

php

math

Given, say, 1.25 - how do I get "1" and ."25" parts of this number?

I need to check if the decimal part is .0, .25, .5, or .75.

like image 877
StackOverflowNewbie Avatar asked Jul 08 '11 02:07

StackOverflowNewbie


People also ask

How do you find the decimal part of a number?

An alternative approach is to use the modulo operator. Use the modulo (%) operator to get the decimal part of a number, e.g. const decimal = num % 1 . When used with a divisor of 1 , the modulo operator returns the decimal part of the number.

What is whole part and decimal part?

The decimal point is placed in between the ones and the tenths. The whole number is written to the left of the decimal point. The fractional part is written to the right of the decimal point. So, a decimal number looks like: The decimal point makes it easy to read a decimal number.

How do I get the decimal part of a number in Excel?

The TRUNC function simply truncates (i.e. removes) decimal values if they exist – it doesn't do any rounding. The TRUNC function returns the integer portion of the number which is then subtracted from the original value. The result is the decimal portion of the number.

What separates the whole number and the decimal part of a whole number?

For example, 456 is the decimal part in 20.456 The whole and decimal part are separated by a dot (.) known as decimal point. The decimal point separates the whole number part on the left side and decimal part or fractional part on the right part.


2 Answers

$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

like image 152
Brad Christie Avatar answered Sep 19 '22 11:09

Brad Christie


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.

like image 27
shelhamer Avatar answered Sep 18 '22 11:09

shelhamer