【转】JS中处理Number浮点数精度问题
https://github.com/dt-fe/number-precision
~(function(root, factory) {
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof module === "object" && module.exports) {
module.exports = factory();
} else {
root.NP = factory();
}
}(this, function() {
'use strict';
/**
* @ file 解决浮动运算问题,避免小数点后产生多位数和计算精度损失。
* 问题示例:2.3 + 2.4 = 4.699999999999999,1.0 - 0.9 = 0.09999999999999998
*/
return {
/**
* 把错误的数据转正
* strip(0.09999999999999998)=0.1
*/
strip: function (num, precision = 12) {
return +parseFloat(num.toPrecision(precision));
},
/**
* Return digits length of a number
* @ param {*number} num Input number
*/
digitLength: function (num) {
// Get digit length of e
const eSplit = num.toString().split(/[eE]/);
const len = (eSplit[0].split('.')[1] || '').length - (+(eSplit[1] || 0));
return len > 0 ? len : 0;
},
/**
* 精确加法
*/
plus: function (num1, num2) {
const baseNum = Math.pow(10, Math.max(this.digitLength(num1), this.digitLength(num2)));
return (num1 * baseNum + num2 * baseNum) / baseNum;
},
/**
* 精确减法
*/
minus: function (num1, num2) {
const baseNum = Math.pow(10, Math.max(this.digitLength(num1), this.digitLength(num2)));
return (num1 * baseNum - num2 * baseNum) / baseNum;
},
/**
* 精确乘法
*/
times: function (num1, num2) {
const num1Changed = Number(num1.toString().replace('.', ''));
const num2Changed = Number(num2.toString().replace('.', ''));
const baseNum = this.digitLength(num1) + this.digitLength(num2);
return num1Changed * num2Changed / Math.pow(10, baseNum);
},
/**
* 精确除法
*/
divide: function (num1, num2) {
const num1Changed = Number(num1.toString().replace('.', ''));
const num2Changed = Number(num2.toString().replace('.', ''));
return this.times((num1Changed / num2Changed), Math.pow(10, this.digitLength(num2) - this.digitLength(num1)));
},
/**
* 四舍五入
*/
round: function (num, ratio) {
const base = Math.pow(10, ratio);
return this.divide(Math.round(this.times(num, base)), base);
}
};
}));
方法:
NP.strip(num) // strip a number to nearest right number
NP.plus(num1, num2) // addition, num + num2
NP.minus(num1, num2) // subtraction, num1 - num2
NP.times(num1, num2) // multiplication, num1 * num2
NP.divide(num1, num2) // division, num1 / num2
NP.round(num, ratio) // round a number based on ratio 使用:
NP.strip(0.09999999999999998); // =0.1
NP.plus(0.1, 0.2); // =0.3 not 0.30000000000000004
NP.plus(2.3, 2.4); // =4.7 not 4.699999999999999
NP.minus(1.0, 0.9); // =0.1 not 0.09999999999999998
NP.times(3, 0.3); // =0.9 not 0.8999999999999999
NP.times(0.362, 100); // = 36.2, not 36.199999999999996
NP.divide(1.21, 1.1); // =1.1 not 1.0999999999999999
NP.round(0.105, 2); // =0.11 not 0.1
【转】JS中处理Number浮点数精度问题的更多相关文章
- js 中的 number 为何很怪异
js 中的 number 为何很怪异 声明:需要读者对二进制有一定的了解 对于 JavaScript 开发者来说,或多或少都遇到过 js 在处理数字上的奇怪现象,比如: > 0.1 + 0.2 ...
- js中声明Number的五种方式
转载自:http://www.jb51.net/article/34191.htm <!DOCTYPE html> <html> <head> <meta c ...
- JS中如何理解浮点数?
本文由云+社区发表 相信大家在平常的 JavaScript 开发中,都有遇到过浮点数运算精度误差的问题,比如 console.log(0.1+0.2===0.3)// false.在 JavaScri ...
- JS中的Number数据类型详解
Number数据类型 Number类型使用IEEE754格式来表示整数和浮点值,这也是0.2 + 0.3不等于0.5的原因, 最基本的数值类型字面量格式是十进制整数 var a = 10; 1. 浮点 ...
- js中的Number方法
1.Number.toExponential(fractionDigits) 把number转换成一个指数形式的字符串.可选参数控制其小数点后的数字位数.它必须在0~20之间. 例如: documen ...
- Number浮点数运算详解
文章来自我的 github 博客,包括技术输出和学习笔记,欢迎star. 一道题 0.1 + 0.2 = ? 在浏览器中测试下计算结果,得到的结果是 0.30000000000000004,并不是理想 ...
- js浮点数精度丢失问题及如何解决js中浮点数计算不精准
js中进行数字计算时候,会出现精度误差的问题.先来看一个实例: console.log(0.1+0.2===0.3);//false console.log(0.1+0.1===0.2);//true ...
- js中精度问题以及解决方案
js中的数字按照IEEE 754的标准,使用64位双精度浮点型来表示.其中符号位S,指数位E,尾数位M分别占了1,11,52位,并且在ES5规范中指出了指数位E的取值范围是[-1074, 971]. ...
- js中如何取精度
js中如何取精度 一.总结 一句话总结:其实round()函数去经度会有误差,直接用num.toFixed(2)简单方便. toFixed()方法会按照指定的小数返回数值的字符串表示.var num ...
随机推荐
- apt-get linux 虚拟机安装vm tools下载
要重启机器才行D:\Program Files (x86)\linux.iso解压tar zxvf VMwareTools-9.9.0-2304977.tar.gz
- 开始编写Makefile(三)Makefile的默认模式规则
1.make中建立的其他语言的规则 SCCS , RCS , ar, lex 和yacc 命令 2.为了建立一个目标,make会遍历一连串的依赖关系:这个是为 决定何处开始创建: 如果没有找到目标文 ...
- C语言中一个字符对应一个ascii码;占一个1个字节8个二进制位;存到内存中也是用ascii的十进制的二进制表示
/** 只读变量和常量 const 只读 const int a; int const a;//同上面的代码行是等价的,都表示一个常整形数. int *const a;//const具有"左 ...
- We found potential security vulnerabilities in your dependencies. Only the owner of this reposito...
删除package-lock.json并同步到git 定义的依赖项./package-lock.json具有已知的安全漏洞 找到一个叫做.gitignore,把package-lock.json贴在这 ...
- [golang]Go内嵌静态资源go-bindata的安装及使用
使用 Go 开发应用的时候,有时会遇到需要读取静态资源的情况.比如开发 Web 应用,程序需要加载模板文件生成输出的 HTML.在程序部署的时候,除了发布应用可执行文件外,还需要发布依赖的静态资源文件 ...
- C Primer Plus--C存储类、链接和内存管理之存储类(storage class)
目录 存储类 作用域 链接 存储时期 自动变量 寄存器变量 具有代码块作用域的静态变量 具有外部链接的静态变量 extern关键字 具有内部链接的静态变量 多文件 存储类 C为变量提供了5种不同的存储 ...
- spark学习记录-1
mapreduce的限制 适合“一趟”计算操作 很难组合和嵌套操作符号 无法表示迭代操作 ======== 由于复制.序列化和磁盘IO导致mapreduce慢 复杂的应用.流计算.内部查询都因为map ...
- Nfs固定端口 nfs 端口公网映射
- SpringCloud-Eureka配置instanceId显示IP
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ instance: preferIpAddress: tr ...
- MyBatis的学习总结:调用存储过程【参考】
一.创建存储过程 存储过程的目的:统计edi_test_task 正在运行的任务和非运行的任务 CREATE DEFINER=`root`@`%` PROCEDURE `edihelper`.`SP_ ...