Skip to content

Instantly share code, notes, and snippets.

@Ai01
Last active August 2, 2017 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ai01/17ed7aa7dedeabae576420c507868a07 to your computer and use it in GitHub Desktop.
Save Ai01/17ed7aa7dedeabae576420c507868a07 to your computer and use it in GitHub Desktop.
js浮点数计算
// 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