在PHP中为浮点数设置精度 [英] Set precision for a float number in PHP

查看:530
本文介绍了在PHP中为浮点数设置精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库中获得了一个号码,这个号码可能是floatint.

我需要将数字的小数精度设置为3,这使得数字不超过(关于小数)5.0201518845.756.

I get a number from database and this number might be either float or int.

I need to set the decimal precision of the number to 3, which makes the number not longer than (regarding decimals) 5.020 or 1518845.756.

使用PHP

round($number, $precision)

我看到一个问题:

将数字四舍五入.我需要一个仅将小数点缩短而不更改round( )似乎不遵循的值的函数.

It rounds the number. I need a function to only cut the decimals short, without changing their values which round( ) seems not to follow.

推荐答案

您可以使用 number_format() 来实现这个:

You can use number_format() to achieve this:

echo number_format((float) $number, $precision, '.', ''); 

这会将1518845.756789转换为1518845.757.

但是,如果您只想将小数位数减少到3个,并且 舍入,则可以执行以下操作:

But if you just want to cut off the number of decimal places short to 3, and not round, then you can do the following:

$number = intval($number * ($p = pow(10, $precision))) / $p;

乍一看可能令人生畏,但是这个概念确实很简单.您有一个数字,将其乘以10 3 (它变为1518845756.789),将其强制转换为整数,以便删除小数点后3位后的所有内容(成为1518845756),然后除以结果减去10 3 (成为1518845.756).

It may look intimidating at first, but the concept is really simple. You have a number, you multiply it by 103 (it becomes 1518845756.789), cast it to an integer so everything after the 3 decimal places is removed (becomes 1518845756), and then divide the result by 103 (becomes 1518845.756).

演示

这篇关于在PHP中为浮点数设置精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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