可以从两个整型变量的和中得到浮点型结果吗?
示例:
1 + 2 => 3.0我尝试过使用number_format($result, 1)和sprintf("%.1f", $result),但返回值类型为string。
此外,如果我将cast类型转换为浮点型,则返回值是值为3而不是3.0的浮点型
发布于 2017-12-28 17:49:45
我建议你..你可以使用sprintf:
$a = 1+2;
$result = sprintf("%.2f", $a); //3.00 or $result = sprintf("%.1f", $a); //3.0
echo $result; 希望它能帮上忙!
发布于 2017-12-28 17:28:19
使用floatval();将值切换为浮点型
另外,请查看类似的问题PHP - Force integer conversion to float with three decimals
发布于 2017-12-28 17:47:27
整型变量的类型为int
如果你添加两个int类型,结果必然是一个整数结果。
$intOne = 1;
$intTwo = 2;
$result = $intOne + $intTwo; // = (int)3 你可以很容易地改变你的结果的类型,但是,如果你在你的变量中存储一个int类型,这并不是必须的。
$floatResult = (float) $result; // (float)3另外,如果你不知道你的变量的类型,你可以像这样使用函数'floatval‘(官方文档here):
$floatOne = floatval('3.14'); // (float)3.14
$floatTwo = floatval("3.141 is a Pi number"); // (float)3.14在这种情况下,如果添加两个float类型,则结果为float two:
$result = $floatOne + floatTwo; // (float)6.281最佳实践希望在您的变量和数据库中保存正确类型的(有关类型和性能的更多信息,请阅读this )
如果你只想在整数类型后面显示小数,你可以像这样使用number_format()函数(官方文档here):
$decimalResult = number_format($floatResult, 4);
echo $decimalResult; // Show '3.0000' ^ Number of decimals希望我能帮助你;)
https://stackoverflow.com/questions/48004674
复制相似问题