I need to do this rather strange thing, let’s say i have:
$number = rand(1, 9);
(This is just an example of what number it could be, in reality i get it in entirely different way)
And now i need “convert” that number to 0.2 or whatever number i got, basically it has to begin with 0 and be a float type of number.
PHP does not support explicit type casting in variable declaration. To convert the
intto afloatin the way you want to simply divide by 10:See this page on PHP Type Juggling for more info. If you mix
floatsandintsor other types they will be re-casted. Exmple:Edit: PHP does have explicit type casting, just not in variable declaration. But even if you cast an integer as a float, it won’t display with a decimal place. To do that use PHP’s
number_formatfunction instead:Edit 2: If you simply want to make your number a decimal between 0 and 1 (such that 2 becomes 0.2, 25 becomes 0.25, etc.) you could use the following function:
So
getNumAsDecimal(2)would return0.2.