Skip to content

Commit

Permalink
fix #1 and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jiangtao committed Oct 15, 2017
1 parent 0b99f54 commit ec01337
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 12 deletions.
23 changes: 12 additions & 11 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,23 @@ function digitLength(num) {
return len > 0 ? len : 0;
}

/**
* 精确乘法
*/
function times(num1, num2) {
const num1Changed = Number(num1.toString().replace('.', ''));
const num2Changed = Number(num2.toString().replace('.', ''));
const baseNum = digitLength(num1) + digitLength(num2);
return num1Changed * num2Changed / Math.pow(10, baseNum);
}


/**
* 精确加法
*/
function plus(num1, num2) {
const baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2)));
return (num1 * baseNum + num2 * baseNum) / baseNum;
return (times(num1, baseNum) + times(num2, baseNum)) / baseNum;
}

/**
Expand All @@ -38,16 +49,6 @@ function minus(num1, num2) {
return (num1 * baseNum - num2 * baseNum) / baseNum;
}

/**
* 精确乘法
*/
function times(num1, num2) {
const num1Changed = Number(num1.toString().replace('.', ''));
const num2Changed = Number(num2.toString().replace('.', ''));
const baseNum = digitLength(num1) + digitLength(num2);
return num1Changed * num2Changed / Math.pow(10, baseNum);
}

/**
* 精确除法
*/
Expand Down
2 changes: 1 addition & 1 deletion test/test.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ describe('NP.plus', () => {
check(-3, 7, 4);
check(-221, 38, -183);
check(-1, 0, -1);

check(2.018, 0.001, 2.019);
check(1.3224e10, 1.3224e3, 13224001322.4);
});
});
Expand Down

0 comments on commit ec01337

Please sign in to comment.