php 如何在php中将浮点值转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16456615/
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
How to convert float value to integer in php?
提问by sajith
I want to convert float value (Eg:1.0000124668092E+14) to Integer in php,what is the best method for this in php.output should be "100001246680920"
我想在php中将浮点值(例如:1.0000124668092E+14)转换为整数,php.output中最好的方法应该是“100001246680920”
回答by pozs
What do you mean by converting?
你说的转换是什么意思?
- casting*:
(int) $float
orintval($float)
- truncating:
floor($float)
(down) orceil($float)
(up) - rounding:
round($float)
- has additional modes, seePHP_ROUND_HALF_...
constants
- 铸造*:
(int) $float
或intval($float)
- 截断:(
floor($float)
向下)或ceil($float)
(向上) - 四舍五入:
round($float)
- 有额外的模式,见PHP_ROUND_HALF_...
常量
*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.
*:转换有一些机会,浮点值不能用 int 表示(太大或太小),f.ex。在你的情况下。
PHP_INT_MAX
: The largest integer supported in this build of PHP. Usually int(2147483647).
PHP_INT_MAX
: 此 PHP 版本支持的最大整数。通常是 int(2147483647)。
But, you could use the BCMath, or the GMPextensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)
回答by Mr. Alien
Use round()
用 round()
$float_val = 4.5;
echo round($float_val);
You can also set param for precision and rounding mode, for more info
您还可以为精度和舍入模式设置参数,以获取更多信息
Update (According to your updated question):
更新(根据您更新的问题):
$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201
回答by JamLizzy101
There is always intval() - Not sure if this is what you were looking for...
总是有 intval() - 不确定这是否是您要找的...
example: -
例子: -
$floatValue = 4.5;
echo intval($floatValue); // Returns 4
It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.
它不会将值四舍五入为整数,但会去除小数和尾随数字,并返回小数前的整数。
Here is some documentation for this: - http://php.net/manual/en/function.intval.php
回答by William Desportes
I just want to WARNyou about:
我只想警告你:
>>> (int) (290.15 * 100);
=> 29014
>>> (int) round((290.15 * 100), 0);
=> 29015
回答by fullybaked
Use round
, floor
or ceil
methods to round it to the closest integer, along with intval()
which is limited.
使用round
,floor
或ceil
方法将其四舍五入到最接近的整数,同时intval()
有限。
http://php.net/manual/en/function.round.php
http://php.net/manual/en/function.round.php
http://php.net/manual/en/function.ceil.php
http://php.net/manual/en/function.ceil.php