js 单精度浮点数转10进制_【转】JS中处理Number浮点数精度问题

这篇博客介绍了一个JavaScript库,用于解决在浮点数运算中常见的精度损失问题。它提供了strip、digitLength、plus、minus、times和divide等方法,确保计算结果的准确性。例如,通过调整数字的精度来避免2.3 + 2.4不等于4.6的情况。此外,还提供了四舍五入的round方法。
摘要由CSDN通过智能技术生成

~(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

*/github

return {

/**

* 把错误的数据转正

* strip(0.09999999999999998)=0.1

*/

strip: function (num, precision = 12) {

return +parseFloat(num.toPrecision(precision));

},ide

/**

* 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;

},this

/**

* 精确加法

*/

plus: function (num1, num2) {

const baseNum = Math.pow(10, Math.max(this.digitLength(num1), this.digitLength(num2)));

return (num1 * baseNum + num2 * baseNum) / baseNum;

},spa

/**

* 精确减法

*/

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

},rest

/**

* 精确除法

*/

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

},code

/**

* 四舍五入

*/

round: function (num, ratio) {

const base = Math.pow(10, ratio);

return this.divide(Math.round(this.times(num, base)), base);

}

};

}));blog

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值