简体   繁体   English

PHP:将数字四舍五入为16位小数

[英]PHP: rounding a number into 16 decimal digits

Hi I'm trying to rounding a number into the 16 decimal digits but it only show and doesn't round up till 14 decimal digit . 嗨我正在尝试将一个数字四舍五入为16位小数但它只显示并且不会向上舍入到14位十进制数字

Here's my attempt: 这是我的尝试:

<?php

$num= 0.16346153846153846;

$round = number_format((float)$num, 17, '.', '');

echo $round * -1;
?>

OUTPUT: OUTPUT:

-0.16346153846154 -0.16346153846154

EXPECTED OUTPUT: 预期产量:

0.1634615384615385 0.1634615384615385

I know that float is only 14 decimal digits. 我知道浮点数只有14位小数。 Is there any other way around for the 16 decimal digits ? 16位十进制数字还有其他方法吗?

You can set this parameters at run-time. 您可以在运行时设置此参数。 16 digits is usually the maximum value on most platforms, larger values giving only meaningless or "fictional" digits: 16位数通常是大多数平台上的最大值,较大的值只给出无意义或“虚构”数字:

ini_set("precision", "16");

See Changing precision level floating-point variables 请参见更改精度级别浮点变量

Can you try doing this, & see what happens? 你能尝试这样做,看看会发生什么? (May not be the best way of dealing with floats and numbers though) (虽然可能不是处理花车和数字的最好方法)

$num = 0.16346153846153846;
$new_num = $num * -1;
echo number_format((float)$new_num, 17);

Multiply first, then try rounding the result. 首先乘以,然后尝试舍入结果。

number_format and the precision INI setting uses float , which is likely to result in unexpected behaviour if you're rounding to that many decimal digits. number_formatprecision INI设置使用float ,如果你四舍五入到那么多十进制数字,这可能会导致意外行为。

You can alternatively use the PHP decimal extension with $decimal->toFixed(16) or $decimal->round(16) to achieve this with guaranteed accuracy regardless of your INI. 您也可以使用带有$decimal->toFixed(16)$decimal->round(16)PHP十进制扩展来保证准确性,无论您的INI如何。

Recently we experienced an issue with the reading of amount(decimal number) from an excel file which has a decimal number with more than 14 digits after the decimal. 最近我们遇到了一个从excel文件中读取金额(十进制数)的问题,该文件的十进制数小于14位。 The issue is fixed after using the option of an advanced algorithm for converting the decimal number. 使用高级算法选项转换十进制数后,问题得以解决。 For this, we need to set, 为此,我们需要设置,

ini_set('precision', -1); ini_set('precision', - 1);

Ref: http://php.net/precision 参考: http//php.net/precision

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM