0

I am trying to get the first decimal place of a float number as an integer by subtracting the integer part, multiplying the remainder with 10 and then casting the result to int or using intval(). I noticed that the result for numbers with x.1 is correctly 1 as float, but after converting it to integer, it becomes sometimes 0, sometimes 1.

I tried to test it with numbers from 1.1 to 9.1:

for ($number = 1; $number < 10; $number++) {
    $result = 10 * ($number + 0.1 - $number);
    echo "<br/> number = " . ($number + 0.1) . ", result: ";
    var_dump($result);
    $result_int = intval($result);
    var_dump($result_int);
}

Starting with 4.1 as input, the 1 oddly gets converted to 0:

number = 1.1, result: float(1) int(1)
number = 2.1, result: float(1) int(1)
number = 3.1, result: float(1) int(1)
number = 4.1, result: float(1) int(0)
number = 5.1, result: float(1) int(0)
number = 6.1, result: float(1) int(0)
number = 7.1, result: float(1) int(0)
number = 8.1, result: float(1) int(0)
number = 9.1, result: float(1) int(0)  

Why at 4.1? That doesn't make any sense to me. Can anyone give me a hint what I am doing wrong?

PS: also tested at http://ideone.com/hr7M0A

xtoph
  • 3
  • 1

2 Answers2

0

My php is a bit rusty, so my syntax in probably off, but shouldn't it be simpler to convert to string and take the rightmost digit ?

sprintf($Str, "%.1f", $number);
$digit=$Str[strlen($Str)-1]; // Last digit
dargaud
  • 2,431
  • 2
  • 26
  • 39
  • Yeah, I assume that would also work - thanks! I just wanted to stay with numbers (better adaptible to other cases) and find out if I had a fundamental flaw in my code. – xtoph Jan 21 '15 at 16:05
0

You are seeing these results because floating point arithmetic is not perfectly accurate.

Instead of trying to manually get the first decimal point use fmod:

$result = substr(fmod($number, 1) * 10, 0, 1)
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Thank you, that works. ($number would be $number + 0.1 in my snippet above). I also found out that applying round() to the float before converting leads to correct results. – xtoph Jan 21 '15 at 15:32