PHP轮到整数 [英] PHP round to integer

查看:155
本文介绍了PHP轮到整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个数字,我需要一个适当的整数,因为我想用它作为数组键。想到的第一个解决方案是:
$ b $ $ $ p $ $ c $ $ $ key =(int)round($ number)

但是,我不确定这是否会始终有效。据我所知(int)只是截断任何小数,因为 round($ number)返回理论上的浮点数有限的精度,有可能是 round($ number)返回类似于7.999999 ...然后 $ key 是7而不是8?



如果这个问题确实存在(我不知道该如何测试),那该如何解决呢?也许:
$ b $ pre $ $ c $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b

有没有比这更好的解决方案?

解决方案

要正确地舍入浮点数,可以使用:



这些函数返回float,但是来自 Niet the Dark Absol评论: em>存储在浮点数中的整数总是精确的,高达2 ^ 51左右,这是很多无论如何都可以存储在一个int中。


I want to round a number and I need a proper integer because I want to use it as an array key. The first "solution" that comes to mind is:

$key = (int)round($number)

However, I am unsure if this will always work. As far as I know (int) just truncates any decimals and since round($number) returns a float with theoretically limited precision, is it possible that round($number) returns something like 7.999999... and then $key is 7 instead of 8?

If this problem actually exists (I don't know how to test for it), how can it be solved? Maybe:

$key = (int)(round($number) + 0.0000000000000000001) // number of zeros chosen arbitrarily

Is there a better solution than this?

解决方案

To round floats properly, you can use:

Those functions return float, but from Niet the Dark Absol comment: "Integers stored within floats are always accurate, up to around 2^51, which is much more than can be stored in an int anyway."

这篇关于PHP轮到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆