将 int 转换为浮点数,PHP 中的两个十进制值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12993689/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:36:00  来源:igfitidea点击:

Cast int to float, two decimal values in PHP

phpcastingintegerdecimal-point

提问by menislici

Possible Duplicate:
PHP: show a number to 2 decimal places

可能的重复:
PHP:显示一个数字到小数点后两位

How do I cast an integer, let's say $i=50to a float with two decimal values: $m=50.00? I have tried (float)$ibut nothing happens.

我如何转换一个整数,让我们说$i=50一个带有两个十进制值的浮点数:$m=50.00?我试过了,(float)$i但没有任何反应。

EDIT:

编辑:

I need to make $i == $mso that returns TRUE;

我需要做出$i == $m这样的回报TRUE

回答by davepmiller

round((float)$i, 2) Should do the trick.

round((float)$i, 2) 应该可以解决问题。

The round function is built in and rounds a given float to the number of decimal places specified in the given argument.

round 函数是内置的,它将给定的浮点数四舍五入到给定参数中指定的小数位数。

Ahh yes, number_format($var, 2) is good as well !

啊,是的, number_format($var, 2) 也不错!

回答by nyson

If you're just using the regular equality operator (==) instead of the type-safe equality operator (===) you shouldn't have any problems.

如果您只是使用常规等式运算符 ( ==) 而不是类型安全的等式运算符 ( ===) ,您应该不会有任何问题。

Comparing a double to an int with the same values:

将 double 与具有相同值的 int 进行比较:

$i = 20;
$m = 20.00;

gettype($i); // integer
gettype($m); // double

$i == $m; // true;
$i === $m; // false, $m is a double and $i is an integer.

If we would like to fix that, however, we just need to do:

但是,如果我们想解决这个问题,我们只需要执行以下操作:

$i = (double)$i;
gettype($i); // double
$i === $m; // true!

回答by Joey

For floating point numbers the number of decimal digits is a formatting property, that is the number itself doesn't know about those things. A float50 is stored as an exact integer 50. You need to formatthe number (using sprintffor example) to be written with decimal digits.

对于浮点数,十进制数字的数量是一种格式属性,即数字本身不知道这些事情。甲float50存储为一个准确的整数50.你需要格式化的数量(使用sprintf例如)与十进制数字被写入。