Usually, a floating point calculation error occurs in a programming language.
var x = 0.2 + 0.1; // 0.3
console.log(x) // 0.30000000000000004
var y = 0.1 * 0.2; // 0.02
console.log(y) // 0.020000000000000004
To compensate for these errors, the following functions are used:
var fpCalc = function (op, x, y) {
var xexp = Math.pow(10, String(x).length - String(x).indexOf('.') - 1),
yexp = Math.pow(10, String(y).length - String(y).indexOf('.') - 1);
var tens = Math.max(100, xexp, yexp);
var n = 0;
switch(op) {
case '*': n = x * y;
break;
case '-': n = x - y;
break;
case '+': n = x + y;
break;
case '/': n = x / y;
break;
default:
return NaN;
}
return Math.round(n * tens) / tens;
};
console.log(fpCalc('+', 0.1, 0.2));
console.log(fpCalc('+', 707.4, 226.2));
console.log(fpCalc('*', 0.1, 0.2));
console.log(fpCalc('/', 214500, 1.1));
It's complicated a lot, I'd like to know if there's any other way or library.
javascript
http://jsbin.com/devacu/edit?html,output Please test it here
More
mathjs is quite complicated in the calculation of the rules
If you look at the link, you should choose one of the three modules and use it
https://github.com/MikeMcl/big.js/wiki
© 2024 OneMinuteCode. All rights reserved.