在JavaScript中输出下面这些数值(注意不能作为字符串输出):0.1000000000000000000000000001(28位小数)、0.100000000000000000000000001(27位小数)、0.1000000000000000000000000456(28位小数)、0.09999999999999999999999(23位小数),显示出来的结果都是数值0.1。又如,如果输出1/3的有理数表达式,结果是0.3333333333333333。 document.write(.1 + .2) // 0.3000000000000004

document.write(.3 + .6) // 0.8999999999999999

Some statistics related to this famous double precision question. I used this code.

When adding all values (a+b) using a step of 0.1 (from 0.1 to 100) we have ~15% chance of precision error. Here are some examples (for full .txt results here):

0.1 + 0.2 = 0.30000000000000004
0.1 + 0.7 = 0.7999999999999999
...
1.7 + 1.9 = 3.5999999999999996
1.7 + 2.2 = 3.9000000000000004
...
3.2 + 3.6 = 6.800000000000001
3.2 + 4.4 = 7.6000000000000005

When subtracting all values (a-b where a>b) using a step of 0.1 (from 100 to 0.1) we have ~34% chance of precision error. Here are some examples (for full .txt results here):

0.6 - 0.2 = 0.39999999999999997
0.5 - 0.4 = 0.09999999999999998
...
2.1 - 0.2 = 1.9000000000000001
2.0 - 1.9 = 0.10000000000000009
...
100 - 99.9 = 0.09999999999999432
100 - 99.8 = 0.20000000000000284

*I was surprised with these 15% and 34%.. they are huge, so always use BigDecimal when precision is of big importance. With 2 decimal digits (step 0.01) the situation worsens a bit more (18% and 36%).

 
 1 /**
2 ** 加法函数,用来得到精确的加法结果
3 ** 说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
4 ** 调用:accAdd(arg1,arg2)
5 ** 返回值:arg1加上arg2的精确结果
6 **/
7 function accAdd(arg1, arg2) {
8 var r1, r2, m, c;
9 try {
10 r1 = arg1.toString().split(".")[1].length;
11 }
12 catch (e) {
13 r1 = 0;
14 }
15 try {
16 r2 = arg2.toString().split(".")[1].length;
17 }
18 catch (e) {
19 r2 = 0;
20 }
21 c = Math.abs(r1 - r2);
22 m = Math.pow(10, Math.max(r1, r2));
23 if (c > 0) {
24 var cm = Math.pow(10, c);
25 if (r1 > r2) {
26 arg1 = Number(arg1.toString().replace(".", ""));
27 arg2 = Number(arg2.toString().replace(".", "")) * cm;
28 } else {
29 arg1 = Number(arg1.toString().replace(".", "")) * cm;
30 arg2 = Number(arg2.toString().replace(".", ""));
31 }
32 } else {
33 arg1 = Number(arg1.toString().replace(".", ""));
34 arg2 = Number(arg2.toString().replace(".", ""));
35 }
36 return (arg1 + arg2) / m;
37 }
38
39 //给Number类型增加一个add方法,调用起来更加方便。
40 Number.prototype.add = function (arg) {
41 return accAdd(arg, this);
42 };
 1 /**
2 ** 减法函数,用来得到精确的减法结果
3 ** 说明:javascript的减法结果会有误差,在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
4 ** 调用:accSub(arg1,arg2)
5 ** 返回值:arg1加上arg2的精确结果
6 **/
7 function accSub(arg1, arg2) {
8 var r1, r2, m, n;
9 try {
10 r1 = arg1.toString().split(".")[1].length;
11 }
12 catch (e) {
13 r1 = 0;
14 }
15 try {
16 r2 = arg2.toString().split(".")[1].length;
17 }
18 catch (e) {
19 r2 = 0;
20 }
21 m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
22 n = (r1 >= r2) ? r1 : r2;
23 return ((arg1 * m - arg2 * m) / m).toFixed(n);
24 }
25
26 // 给Number类型增加一个mul方法,调用起来更加方便。
27 Number.prototype.sub = function (arg) {
28 return accMul(arg, this);
29 };
 1 /**
2 ** 乘法函数,用来得到精确的乘法结果
3 ** 说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
4 ** 调用:accMul(arg1,arg2)
5 ** 返回值:arg1乘以 arg2的精确结果
6 **/
7 function accMul(arg1, arg2) {
8 var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
9 try {
10 m += s1.split(".")[1].length;
11 }
12 catch (e) {
13 }
14 try {
15 m += s2.split(".")[1].length;
16 }
17 catch (e) {
18 }
19 return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
20 }
21
22 // 给Number类型增加一个mul方法,调用起来更加方便。
23 Number.prototype.mul = function (arg) {
24 return accMul(arg, this);
25 };
 1 /**
2 ** 除法函数,用来得到精确的除法结果
3 ** 说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
4 ** 调用:accDiv(arg1,arg2)
5 ** 返回值:arg1除以arg2的精确结果
6 **/
7 function accDiv(arg1, arg2) {
8 var t1 = 0, t2 = 0, r1, r2;
9 try {
10 t1 = arg1.toString().split(".")[1].length;
11 }
12 catch (e) {
13 }
14 try {
15 t2 = arg2.toString().split(".")[1].length;
16 }
17 catch (e) {
18 }
19 with (Math) {
20 r1 = Number(arg1.toString().replace(".", ""));
21 r2 = Number(arg2.toString().replace(".", ""));
22 return (r1 / r2) * pow(10, t2 - t1);
23 }
24 }
25
26 //给Number类型增加一个div方法,调用起来更加方便。
27 Number.prototype.div = function (arg) {
28 return accDiv(this, arg);
29 };
 
高级浏览器解决方法:
 
function strip(number) {
return (parseFloat(number.toPrecision(12)));
}

Using 'toPrecision(12)' leaves trailing zeros which 'parseFloat()' removes. Assume it is accurate to plus/minus one on the least significant digit.

定义和用法

toPrecision() 方法可在对象的值超出指定位数时将其转换为指数计数法。

语法

NumberObject.toPrecision(num)
参数 描述
num 必需。规定必须被转换为指数计数法的最小位数。该参数是 1 ~ 21 之间(且包括 1 和 21)的值。有效实现允许有选择地支持更大或更小的 num。如果省略了该参数,则调用方法 toString(),而不是把数字转换成十进制的值。

返回值

返回 NumberObject 的字符串表示,包含 num 个有效数字。如果 num 足够大,能够包括 NumberObject 整数部分的所有数字,那么返回的字符串将采用定点计数法。否则,采用指数计数法,即小数点前有一位数字,小数点后有 num-1 位数字。必要时,该数字会被舍入或用 0 补足。

抛出

当 num 太小或太大时抛出异常 RangeError。1 ~ 21 之间的值不会引发该异常。有些实现支持更大范围或更小范围内的值。

当调用该方法的对象不是 Number 时抛出 TypeError 异常。

实例

在本例中,我们将把一个数字转换为指数计数法:

Show 10,000 as an exponential notation:
<script type="text/javascript">
var num = new Number(10000);
document.write (num.toPrecision(4))
</script>

输出:

Show 10,000 as an exponential notation:
1.000e+4 同时还可以使用一个https://github.com/MikeMcl/bignumber.js 插件来完成JS精度运算的BUG

Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal
8 KB minified and gzipped
Simple API but full-featured
Works with numbers with or without fraction digits in bases from 2 to 64 inclusive
Replicates the toExponential, toFixed, toPrecision and toString methods of JavaScript's Number type
Includes a toFraction and a correctly-rounded squareRoot method
Supports cryptographically-secure pseudo-random number generation
No dependencies
Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only
Comprehensive documentation and test set
API

If a smaller and simpler library is required see big.js. It's less than half the size but only works with decimal numbers and only has half the methods. It also does not allow NaN or Infinity, or have the configuration options of this library.

Use

In all examples below, var, semicolons and toString calls are not shown. If a commented-out value is in quotes it means toString has been called on the preceding expression.

The library exports a single function: BigNumber, the constructor of BigNumber instances.

It accepts a value of type number (up to 15 significant digits only), string or BigNumber object,

x = new BigNumber(123.4567)
y = BigNumber('123456.7e-3')
z = new BigNumber(x)
x.equals(y) && y.equals(z) && x.equals(z) // true
and a base from 2 to 64 inclusive can be specified.

x = new BigNumber(1011, 2) // "11"
y = new BigNumber('zz.9', 36) // "1295.25"
z = x.plus(y) // "1306.25"
A BigNumber is immutable in the sense that it is not changed by its methods.

0.3 - 0.1 // 0.19999999999999998
x = new BigNumber(0.3)
x.minus(0.1) // "0.2"
x // "0.3"
The methods that return a BigNumber can be chained.

x.dividedBy(y).plus(z).times(9).floor()
x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').ceil()
Many method names have a shorter alias.

x.squareRoot().dividedBy(y).toPower(3).equals(x.sqrt().div(y).pow(3)) // true
x.cmp(y.mod(z).neg()) == 1 && x.comparedTo(y.modulo(z).negated()) == 1 // true
Like JavaScript's number type, there are toExponential, toFixed and toPrecision methods

x = new BigNumber(255.5)
x.toExponential(5) // "2.55500e+2"
x.toFixed(5) // "255.50000"
x.toPrecision(5) // "255.50"
x.toNumber() // 255.5
and a base can be specified for toString.

x.toString(16) // "ff.8"
There is also a toFormat method which may be useful for internationalisation

y = new BigNumber('1234567.898765')
y.toFormat(2) // "1,234,567.90"
The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the config method of the BigNumber constructor.

The other arithmetic operations always give the exact result.

BigNumber.config({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 })
// Alternatively, BigNumber.config( 10, 4 );

x = new BigNumber(2);
y = new BigNumber(3);
z = x.div(y) // "0.6666666667"
z.sqrt() // "0.8164965809"
z.pow(-3) // "3.3749999995"
z.toString(2) // "0.1010101011"
z.times(z) // "0.44444444448888888889"
z.times(z).round(10) // "0.4444444445"
There is a toFraction method with an optional maximum denominator argument

y = new BigNumber(355)
pi = y.dividedBy(113) // "3.1415929204"
pi.toFraction() // [ "7853982301", "2500000000" ]
pi.toFraction(1000) // [ "355", "113" ]
and isNaN and isFinite methods, as NaN and Infinity are valid BigNumber values.

x = new BigNumber(NaN) // "NaN"
y = new BigNumber(Infinity) // "Infinity"
x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true
The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign.

x = new BigNumber(-123.456);
x.c // [ 123, 45600000000000 ] coefficient (i.e. significand)
x.e // 2 exponent
x.s // -1 sign
Multiple BigNumber constructors can be created, each with their own independent configuration which applies to all BigNumber's created from it.

// Set DECIMAL_PLACES for the original BigNumber constructor
BigNumber.config({ DECIMAL_PLACES: 10 })

// Create another BigNumber constructor, optionally passing in a configuration object
BN = BigNumber.another({ DECIMAL_PLACES: 5 })

x = new BigNumber(1)
y = new BN(1)

x.div(3) // '0.3333333333'
y.div(3) // '0.33333'
For futher information see the API reference in the doc directory.

 
分类: JavaScript

解决JS浮点数(小数)计算加减乘除的BUG的更多相关文章

  1. 解决JavaScript浮点数(小数) 运算出现Bug的方法

    解决JS浮点数(小数) 运算出现Bug的方法例如37.2 * 5.5 = 206.08 就直接用JS算了一个结果为: 204.60000000000002 怎么会这样, 两个只有一位小数的数字相乘, ...

  2. 学以致用:手把手教你撸一个工具库并打包发布,顺便解决JS浮点数计算精度问题

    本文讲解的是怎么实现一个工具库并打包发布到npm给大家使用.本文实现的工具是一个分数计算器,大家考虑如下情况: \[ \sqrt{(((\frac{1}{3}+3.5)*\frac{2}{9}-\fr ...

  3. 封装加减乘除函数 解决JS 浮点数计算 Bug

    计算机内部的信息都是由二进制方式表示的,即0和1组成的各种编码,但由于某些浮点数没办法用二进制准确的表示出来,也就带来了一系列精度问题.当然这也不是JS独有的问题. 例如, 我们在用JS做浮点运算会遇 ...

  4. js浮点数的计算

        js在计算浮点数时可能不够准确,会产生舍入误差的问题,这是使用基于IEEE745数值的浮点计算的通病,并非ECMAScript一家,其他使用相同数值格式的语言也存在这个问题.     这里讲一 ...

  5. Javascript优化后的加减乘除(解决js浮点数计算bug)

    function add(a, b) { var c, d, e; try { c = a.toString().split(".")[1].length; } catch (f) ...

  6. 解决js浮点数计算bug

    1.加 function add(a, b) { var c, d, e; try { c = a.toString().split(".")[1].length; } catch ...

  7. js 浮点小数计算精度问题 parseFloat 精度问题

    在js中进行以元为单位进行金额计算时 使用parseFloat会产生精度问题 var price = 10.99; var quantity = 7; var needPay = parseFloat ...

  8. js浮点数的计算总结

    在js浮点值的计算中,很多时候会出现不准确的情况,如下面的情况 console.log(2.2 + 2.1) // 4.300000000000001 console.log(2.2 - 1.9) / ...

  9. 有效解决js中添加border后动画bug问题

    做了个demo发现如果一个div不加border属性,用对象的offsetWidth属性来控制width没问题,但是如果一旦加了border属性,问题就来了. 其实offsetWidth属性获取的的是 ...

随机推荐

  1. UVA 10405最长公共子序列

    裸最长公共子序列,直接贴代码 #include<cstdio> #include<iostream> #include<algorithm> #include< ...

  2. oracle一点记录

    查看数据库实例名(SERVICE_NAME): sql: select instance_name from v$instance; 如何知道oracle客户端是32位还是64的.windows下启动 ...

  3. 关于 redis、memcache、mongoDB 的对比(转载)

    from:http://yang.u85.us/memcache_redis_mongodb.pdf 从以下几个维度,对 redis.memcache.mongoDB 做了对比.1.性能都比较高,性能 ...

  4. 在ubuntu上搭建开发环境4---ubuntu简单的搭建LAMP环境和配置

    最近重新安装了Ubuntu,但是之前的LAMP环境自然也就没有了,实在是不想再去编译搭建LAMP环境(这种方法实在是太费时间,而且太容易遇到各种不知道为什么的错误),所以,就去查查有没有什么简单的搭建 ...

  5. POJ2406 Power Strings(KMP,后缀数组)

    这题可以用后缀数组,KMP方法做 后缀数组做法开始想不出来,看的题解,方法是枚举串长len的约数k,看lcp(suffix(0), suffix(k))的长度是否为n- k ,若为真则len / k即 ...

  6. IBM Rational AppScan 无法记录登录序列 分类: 数据安全 2015-03-18 16:46 158人阅读 评论(0) 收藏

    为了测试漏洞,我在本地部署了一个站点,为http://localhost/app,并且有登录页面. 但是尝试多次,都无法记录登录页面.此时尝试了在hosts文件中,自定义了一个域名 127.0.0.1 ...

  7. C# SMTP邮件发送 分类: C# 2014-07-13 19:10 334人阅读 评论(1) 收藏

    邮件发送在网站应用程序中经常会用到,包括您现在看到的博客,在添加评论后,系统会自动发送邮件通知到我邮箱的,把系统发送邮件的功能整理了下,做了一个客户端Demo,希望对有需要的童鞋有所帮助: 核心代码: ...

  8. C# DatrgridView表格控件的一些用法

    public class useDatrgrivView { string conn = null; string sqlComm = null; DataSet das = null; DataGr ...

  9. [Outlook]设置邮件自动接收时间

    [Outlook]设置邮件自动接收时间   找了好久,一直都没设置正常,导致老是收到邮件有延迟,今天头脑清晰,搜了一下,然后自己竟然给找到了,记下来当笔记,好记性不如烂笔头,呵呵   搜索百度&quo ...

  10. 字节流、字符串、16进制字符串转换__Java(转)

    /** * @Package: * @ClassName:TypeConversion * @Description:字节流.字符串.16进制字符串转换 * @author:xk * @date:Ja ...