Last active
August 2, 2017 10:35
-
-
Save Ai01/17ed7aa7dedeabae576420c507868a07 to your computer and use it in GitHub Desktop.
js浮点数计算
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// js浮点数精确计算。需要在支持static method和class的js环境中运行 | |
// 可以拆分为4个方法(在不支持class和static method)的环境中 | |
// 需要继续完善的是如果x,y中存在几十位的小数那么可能超过安全数字 | |
class Calculate { | |
// x,y是运算数字,n是精度 | |
static add(x, y, n) { | |
const _arg1 = x.toString(); | |
const _arg2 = y.toString(); | |
const arg1Arr = _arg1.split('.'); | |
const arg2Arr = _arg2.split('.'); | |
const d1 = arg1Arr.length === 2 ? arg1Arr[1] : ''; | |
const d2 = arg2Arr.length === 2 ? arg2Arr[1] : ''; | |
const maxLen = Math.max(d1.length, d2.length); | |
const m = 10 ** maxLen; | |
const result = Number(((x * m + y * m) / m).toFixed(maxLen)); | |
return typeof n === 'number' ? Number((result).toFixed(n)) : result; | |
} | |
static sub(x, y, n) { | |
return Calculate.add(x, -y, n); | |
} | |
static mul(x, y, n) { | |
const r1 = x.toString(); | |
const r2 = y.toString(); | |
const m = (r1.split('.')[1] ? r1.split('.')[1].length : 0) + (r2.split('.')[1] ? r2.split('.')[1].length : 0); | |
const resultVal = Number(r1.replace('.', '')) * Number(r2.replace('.', '')) / (10 ** m); | |
return typeof n !== 'number' ? Number(resultVal) : Number(resultVal.toFixed(parseInt(n, 10))); | |
} | |
static div(x, y, n) { | |
const r1 = x.toString(); | |
const r2 = y.toString(); | |
const m = (r2.split('.')[1] ? r2.split('.')[1].length : 0) - (r1.split('.')[1] ? r1.split('.')[1].length : 0); | |
const resultVal = Number(r1.replace('.', '')) / Number(r2.replace('.', '')) * (10 ** m); | |
return typeof n !== 'number' ? Number(resultVal) : Number(resultVal.toFixed(parseInt(n, 10))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment