2012-08-18 20:12

# PHP，将任何数字转换为浮点数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.

• 点赞
• 写回答
• 关注问题
• 收藏
• 复制链接分享
• 邀请回答

#### 3条回答

• douyong5825 9年前

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`.

点赞 评论 复制链接分享
• dongsui0929 9年前
``````function Floatize(){
return (float) (rand(1, 9) / 10);
}

echo Floatize(); // will return something like 0.2 or 0.5 or 0.9
``````
点赞 评论 复制链接分享
• doudun5009 9年前

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

See PHP type casting.

点赞 评论 复制链接分享