ZzozZ ZzozZ - 6 months ago 14
PHP Question

How to turn number from float into closest whole number php?

I have a form where I write a number and then I print other numbers until they reach an "x" number. So when I write 33.3 my output is 34.3, 35.3, 36.3 and etc. If my 'x' number is 100 the last printed number is 99.3 :/ So how can I make it my last printed number to be an int number? And how can I make my second number 34.3 to be 34? If is it possible write some examples :)

Answer

Here is one way to do it.

<?php

$number = 96.3;
$x = 100;

while ($number <= $x) {
    echo $number;
    if ($number != $x) {
        echo ', ';
    }
    $number = intval($number) + 1;
}

Output:

96.3, 97, 98, 99, 100

intval will truncate the fractional part of the number and convert it to an integer. So you just add 1 to that number on each iteration of the loop until you reach x.