Page 1 of 1

How to get a fractional part of a number?

Posted: Mon Jun 16, 2003 3:59 am
by rashed
How to get fractional part of a number?

Posted: Mon Jun 16, 2003 4:01 am
by twigletmac
Could you please elaborate on what you are trying to do. Give an example of a number you want to manipulate and what you want to manipulate it to. It will help us help you if you are more explicit about what you are trying to achieve.

Mac

Posted: Mon Jun 16, 2003 4:09 am
by rashed
Actually, i have to round off the value
like 1.50 becomes 2 and 1.49 remains at 1

I have to calculate percentage based upon this. i have seen ceil(),floor(),round(). If you please help me

Posted: Mon Jun 16, 2003 4:12 am
by Seattlebadboy
That pretty simple.

Here is how it might look:

$value_1 = 1.50;
$value_1 = round( $value_1 );
echo $value_1;
display: 2


$value_1 = 1.49;
$value_1 = round( $value_1 );
echo $value_1;
display: 1

Posted: Mon Jun 16, 2003 4:18 am
by rashed
but how to get the number after the decimal fraction
like in 1.45 .45 how to get this?

Posted: Mon Jun 16, 2003 4:28 am
by Seattlebadboy
Well let's say it's always a 2 digit number after the decimal. Like money. You could do:

// no decimal
$value_1 = 1.43;
$value_1 = substr( $value_1, -2);
echo $value_1;
// displays: 43

// in case you need the decimal
$value_1 = 1.43;
$value_1 = substr( $value_1, -3);
echo $value_1;
// displays: .43

Posted: Mon Jun 16, 2003 4:32 am
by rashed
thank you

Posted: Mon Jun 16, 2003 4:36 am
by Seattlebadboy
Welcome

Posted: Mon Jun 16, 2003 5:03 am
by twigletmac
Something else you can use to split up a number is explode():

Code: Select all

$numbers = array(4.23, 4.5, 3.583, 5);
foreach ($numbers as $number) {
	$num_info = explode('.', $number);
	if (!empty($num_info[1])) {
		echo 'fraction = '.$num_info[1];
	} else {
		echo 'fraction = 0';
	}
	echo '<br />';
}
Mac

Posted: Mon Jun 16, 2003 8:00 am
by bjg
rashed wrote:but how to get the number after the decimal fraction
like in 1.45 .45 how to get this?

Code: Select all

$num = '1.45';
print substr(strstr($num, '.'), 1); // 45
print strstr($num, '.'); // .45

Posted: Mon Jun 16, 2003 8:24 am
by patrikG
Seattlebadboy - could you cut down on the widht of that avatar of yours, please?

Cheers :)

Posted: Mon Jun 16, 2003 8:26 am
by twigletmac
patrikG wrote:Seattlebadboy - could you cut down on the widht of that avatar of yours, please?

Cheers :)
I kinda took action myself (sent you a PM Seattlebadboy). Seems like the forum decided not to stick to the preset avatar limits.

Mac

Posted: Mon Jun 16, 2003 8:56 am
by rashed
Thank you Mac but i think foreach loop takes much CPU cycles than simple conversion from one type to another.

Posted: Mon Jun 16, 2003 10:09 am
by twigletmac
rashed wrote:Thank you Mac but i think foreach loop takes much CPU cycles than simple conversion from one type to another.
The foreach() was just used in the example to show the results from a bunch of different number formats.

Mac