Jump to content

Getting numbers to the left OR right of a decimal?


galvin

Recommended Posts

This is probably super easy, but if I have floats like "5.125", "9.0625", "12.3125", etc, etc, how can I get just the number to the left of the decimal point? If it was alway just one digit to the left, i could handle that (believe it or not  :)). But sometimes it's 1 digit, sometimes 2 digits, possibly even more than 2.  So with those three examples, it would return...

 

5

9

12

 

And while I'm at it, I also need a way to get all the digits to the right of the decimal point. So also need a way to get...

 

125

0625

3125

 

I imagine the answer to one of these is also the answer to the other one, but I don't know either answer :)

 

Can anyone help?

 

Thanks,

Greg

Easiest way to get the number "on the left" would be to cast the float to an integer:

 

<?php
$num = 3.141;
echo (int)$num; //outputs 3

 

An alternative to getting the digits to the right of the decimal:

 

<?php
$num = 3.141;
$num_to_right = ((strpos($num, '.') !== false) ? end(explode('.', $num)) : $num);

echo $num_to_right; //outputs 141

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.