PHP: rounding a number into 16 decimal digits

不羁的心 提交于 2019-12-13 14:18:03

问题


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.

Here's my attempt:

<?php

$num= 0.16346153846153846;

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

echo $round * -1;
?>

OUTPUT:

-0.16346153846154

EXPECTED OUTPUT:

0.1634615384615385

I know that float is only 14 decimal digits. Is there any other way around for the 16 decimal digits?


回答1:


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:

ini_set("precision", "16");

See Changing precision level floating-point variables




回答2:


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.




回答3:


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.

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.




回答4:


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. 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);

Ref: http://php.net/precision



来源:https://stackoverflow.com/questions/27641998/php-rounding-a-number-into-16-decimal-digits

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!