2019年6月

超长精度下前端如何正确回显

之前一篇文章《记一次超长数值精度错误问题》,有记录了下plsql显示值不对的问题。现在问题更大了。前端的json对象解析超长的数值后,居然不是安全数值(随机加减进位),比如我后台给前端传递99,999,999,999,999.99,之后会变成100,000,000,000,000.0。

几近无奈的寻找,终于功夫不负苦心人,我在github上找到一个大数运算的类:decimal.js

https://github.com/MikeMcl/decimal.js

特性如下:
整型,浮点型

快速,简单。

  • Integers and floats
  • Simple but full-featured API
  • Replicates many of the methods of JavaScript's Number.prototype and Math objects
  • Also handles hexadecimal, binary and octal values
  • Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal
  • No dependencies
  • Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only
  • Comprehensive documentation and test set
  • Includes a TypeScript declaration file: decimal.d.ts

使用方法:

x = new Decimal(123.4567)
y = new Decimal('123456.7e-3')
z = new Decimal(x)x.equals(y) && y.equals(z) && x.equals(z)        // true

引用decimal.js后哦,直接new即可。

下面是支持的方法列表

API

<html>
<head>
<title></title>
<script src='decimal.js'></script>
</head>
<body>
<div id="result">
</div>
<script>

var str1='9999999999999999.99';
var bigdecimal = new Decimal(str1);
var msg="<p>当前的数值字符串为:"+str1+"Decimal对象实例化后的toString值为:"+bigdecimal.toString()+"</p>";
//var z = new Decimal(x)
//x.equals(y) && y.equals(z) && x.equals(z)        // true
bigdecimal=bigdecimal.plus(1);
msg=msg+"<p>将值加1后为:"+bigdecimal.toString()+"</p>";
bigdecimal=bigdecimal.minus(1);
msg=msg+"<p>将值减1后为:"+bigdecimal.toString()+"</p>";
bigdecimal=bigdecimal.plus(0.1);
msg=msg+"<p>将值加0.1后为:"+bigdecimal.toString()+"</p>";
bigdecimal=bigdecimal.minus(0.1);
msg=msg+"<p>将值减0.1后为:"+bigdecimal.toString()+"</p>";
bigdecimal=bigdecimal.plus(0.01);
msg=msg+"<p>将值加0.01后为:"+bigdecimal.toString()+"</p>";
var bigdecimal1 = new Decimal("1");

for(var i=1;i<90;i++){
    bigdecimal1=bigdecimal1.mul(2);
    msg=msg+"<p>将值第"+i+"次乘2后为:"+bigdecimal1.toString()+"</p>";
}
document.getElementById("result").innerHTML=msg;

</script>
</body>

</html>