将int转换为float/double

Mik*_*ike 16 php

当我想将integer值转换为float(带点的数字)时,我遇到了麻烦.

$a = 7200;
$b = $a/3600;

echo $b; // 2

$b = floatval($b);

echo $b; // 2
Run Code Online (Sandbox Code Playgroud)

但它应该回应2.02.00

我也试过settype,没有成功.我发现只有"浮动到int"的帮助/解决方案/问题.

Tam*_*n C 31

更新:

使用

echo sprintf("%.2f", $b); // returns 2.00
Run Code Online (Sandbox Code Playgroud)

使用

echo number_format($b, 2);
Run Code Online (Sandbox Code Playgroud)

例如:

echo number_format(1234, 2); // returns 1,234.00
Run Code Online (Sandbox Code Playgroud)

编辑:

@DavidBaucum是的,number_format()返回字符串.

使用

echo sprintf("%.2f", $b);
Run Code Online (Sandbox Code Playgroud)

对于您的问题,请使用

为什么number_format不起作用可以通过这个来证明.echo number_format(1234,0)+ 1.0结果为2

echo sprintf("%.2f",(1234 + 1.0 ) ); // returns 1235.00
Run Code Online (Sandbox Code Playgroud)


Ama*_*ali 8

您可以使用number_format()函数来完成此任务.此函数还允许您定义小数点后要显示的零的数量 - 您只需要使用第二个参数:

$a = 7200;
$b = $a/3600;
$b = floatval($b);
echo number_format($b, 2, '.', '');
Run Code Online (Sandbox Code Playgroud)

或者,如果你想这样做一行:

echo number_format( (float) $b, 2, '.', '');
Run Code Online (Sandbox Code Playgroud)

输出:

2.00
Run Code Online (Sandbox Code Playgroud)

演示!


Bla*_*zer 8

就像是:

<?php
    $a = 7200;
    $b = $a/3600;

    $b = number_format($b,2);

    echo $b; // 2.00
?>
Run Code Online (Sandbox Code Playgroud)

-

number_format(number,decimals,decimalpoint,separator)
Run Code Online (Sandbox Code Playgroud)