PHP舍入错误 [英] PHP rounding error

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

问题描述

我在Linux服务器上使用PHP 5.2.13.四舍五入时出现奇怪的错误.这是我的测试用例:

I'm using PHP 5.2.13 on my linux server. I'm getting weird error when rounding numbers. This is my test case:

<?php
echo "        " . round(1.505, 2) . "\n";
echo "       " . round(11.505, 2) . "\n";
echo "      " . round(111.505, 2) . "\n";
echo "     " . round(1111.505, 2) . "\n";
echo "    " . round(11111.505, 2) . "\n";
echo "   " . round(111111.505, 2) . "\n";
echo "  " . round(1111111.505, 2) . "\n";
echo " " . round(11111111.505, 2) . "\n";
echo "" . round(111111111.505, 2) . "\n";

这是结果:

        1.51
       11.51
      111.51
     1111.51
    11111.51
   111111.51
  1111111.5
 11111111.51
111111111.51

有人知道是什么原因造成的吗?我无法更新PHP,因为它是共享服务器.

Anyone knows what causes this? I can't update PHP, since it's shared server.

推荐答案

这是因为数字1111111.505不能精确地用浮点表示法表示.它可以获取的最接近值为1111111.5049999999.因此,最终发生的事情是将代码中的数字转换为1111111.50499999999,然后进行了四舍五入.结果为1111111.5.浮点数存在一些问题,即它们不能代表很多甚至看似简单的十进制数,而且具有完全的准确性.例如.数字0.1无法使用二进制浮点数精确表示.使用Python,如果输入0.1,则返回0.10000000000001.加上或减去几个零.这就是某些语言(例如.Net)提供十进制"数据类型的原因,该数据类型能够表示特定范围和小数位数内的所有十进制值.十进制数据类型的缺点是速度较慢,每个数字都需要更多的空间来存储.

This is because the number 1111111.505 can't be represented exactly in floating point notation. The closest it can get is 1111111.5049999999. So what ends up happening is that it converts the number in your code to 1111111.50499999999 and then it does the rounding. Which results in 1111111.5. Floating point numbers have problems in that they can't represent a lot of even seemingly simple decimal numbers with complete accuracy. For instance. the number 0.1 cannot be accurately represented using binary floating numbers. Using Python, if you type in 0.1, it returns 0.10000000000001. Plus or minus a few zeros. This is the reason that some languages such as .Net provide a "Decimal" data type which is able to represent all decimal values within a certain range and number of decimal places. The downside of the decimal data type is that it is slower, and each number takes more space to store.

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

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