如何对 bcmath 数字进行向上、向下和舍入?
我需要模仿 ceil() 的确切功能,< a href="http://www.php.net/manual/en/function.floor.php" rel="noreferrer">floor() 和 round() bcmath 数字函数,我已经找到了一个非常类似的问题,但不幸的是提供的答案对我来说不够好,因为它缺乏对负数的支持并且缺少round()函数的精度参数。
我想知道是否有人可以针对这个问题提出一个相当简短而优雅的解决方案。
感谢所有意见,谢谢!
I need to mimic the exact functionality of the ceil(), floor() and round() functions on bcmath numbers, I've already found a very similar question but unfortunately the answer provided isn't good enough for me since it lacks support for negative numbers and the precision argument for the round() function is missing.
I was wondering if anyone can come up with a rather short and elegant solution to this problem.
All input is appreciated, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
经过一晚尝试解决这个问题后,我相信我找到了一个相当简单的解决方案,如下:
我想我没有错过任何东西,如果有人能发现任何错误,请告诉我。以下是一些测试:
After a night lost trying to solve this problem I believe I've found a rather simple solution, here it is:
I think I didn't miss anything, if someone can spot any bug please let me know. Here are some tests:
以下是支持负数和舍入精度参数的参数。
Here's ones that support negative numbers and precision argument for rounding.
我选择 Alix Axel 的变体进行舍入,因为它是最快的,因为它只使用加法和减法,而不使用乘法和除法。为了在开始时以负精度舍入,我使用了标准函数:
但我遇到了描述的问题 此处。因此,我扩展了这个变体以实现负精度:
通过递归的更优雅和更短的选项:
但它速度较慢,因为它使用两个操作(除法和乘法),而不是在第一种情况下查找除法余数(mod)的一个操作。速度测试已经证实了这一点:
第一个变体。总迭代次数:10000。持续时间:0.24502515792847 秒。
第二个变体。总迭代次数:10000。持续时间:0.35303497314453 秒。
I chose the Alix Axel's variant for rounding as it is the fastest since it only uses addition and subtraction, not multiplication and division. To round with negative precision at the beginnig I used standard function:
But I faced the problem described here. So I extended this variant for negative precision:
A more elegant and shorter option through recursion:
But it is slower because it uses two operations (division and multiplication) versus one operation of finding the remainder of the division (mod) in the first case. Speed tests have confirmed this:
First variant. Total iterations:10000. Duration: 0.24502515792847 seconds.
Second variant. Total iterations:10000. Duration: 0.35303497314453 seconds.
仅使用 bcmath 函数来执行此操作:
对于测试:
以及测试结果:
Only use bcmath functions to do that:
For test:
And the test results: