dszpyf4859 2012-08-18 20:12
浏览 96
已采纳

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 2012-08-18 20:17
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用