Linas
Linas

Reputation: 4408

PHP, Convert any number to float 0.x

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.

Upvotes: 0

Views: 1704

Answers (3)

Alex Kalicki
Alex Kalicki

Reputation: 1533

PHP does not support explicit type casting in variable declaration. To convert the int to a float in the way you want to simply divide by 10:

$number = rand(1, 9) / 10;

See this page on PHP Type Juggling for more info. If you mix floats and ints or other types they will be re-casted. Exmple:

echo 10 + 2.5; // gives you 12.5, a float because of the types used

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_format function instead:

echo number_format(10, 1); // gives you 10.0

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:

function getNumAsDecimal($num) {
    return ($num / pow(10, strlen((string)$num)));
}

So getNumAsDecimal(2) would return 0.2.

Upvotes: 4

oxygen
oxygen

Reputation: 6039

$number=(float)rand(1, 9)/10;

See PHP type casting.

Upvotes: 0

Dzhuneyt
Dzhuneyt

Reputation: 8701

function Floatize(){
    return (float) (rand(1, 9) / 10);
}

echo Floatize(); // will return something like 0.2 or 0.5 or 0.9

Upvotes: 0

Related Questions