php 将 int 转换为 float/double
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19409574/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
converting int to float/double
提问by Mike
I am running into troubles when I want to convert integer
values to float
(numbers with dots).
当我想将integer
值转换为float
(带点的数字)时遇到了麻烦。
$a = 7200;
$b = $a/3600;
echo $b; // 2
$b = floatval($b);
echo $b; // 2
But it should echo 2.0
or 2.00
但它应该回声2.0
或2.00
I also tried settype, without success. And I am finding only help/solutions/questions for "float to int".
我也尝试过 settype,但没有成功。我只找到“float to int”的帮助/解决方案/问题。
回答by Tamil Selvan C
Updated:
更新:
Use
用
echo sprintf("%.2f", $b); // returns 2.00
Use
用
echo number_format($b, 2);
eg:
echo number_format(1234, 2); // returns 1,234.00
echo number_format($b, 2);
例如:
echo number_format(1234, 2); // returns 1,234.00
Edit:
编辑:
@DavidBaucum Yes, number_format() returns string.
@DavidBaucum 是的,number_format() 返回字符串。
Use
用
echo sprintf("%.2f", $b);
For your question, use
对于您的问题,请使用
Why number_format doesn't work can be demonstrated by this. echo number_format(1234,0) + 1.0 The result is 2
这可以证明为什么 number_format 不起作用。echo number_format(1234,0) + 1.0 结果是2
echo sprintf("%.2f",(1234 + 1.0 ) ); // returns 1235.00
回答by Amal Murali
You can use number_format()
function to accomplish this. This function also allows you to define the number of zeroes to be displayed after the decimal -- you just need to use the second parameter for that:
您可以使用number_format()
函数来完成此操作。此函数还允许您定义小数点后要显示的零数——您只需要为此使用第二个参数:
$a = 7200;
$b = $a/3600;
$b = floatval($b);
echo number_format($b, 2, '.', '');
Or, if you want to do it one line:
或者,如果你想做一行:
echo number_format( (float) $b, 2, '.', '');
Output:
输出:
2.00
回答by Blazer
Something like:
就像是:
<?php
$a = 7200;
$b = $a/3600;
$b = number_format($b,2);
echo $b; // 2.00
?>
-
——
number_format(number,decimals,decimalpoint,separator)
回答by Mike
I found a solution by myself:
我自己找到了一个解决方案:
$b = number_format((float)$b, 1, '.', '');
echo $b; // 2.0
does the trick
有诀窍