1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title></title> 7 <script> 8 var old = 0.2878978 + 1.89; 9 console.log(old); 10 console.log(strip(old)); 11 var result = plus(0.2878978, 1.89); 12 console.log(result); 13 14 console.log(3.1415926 * 79.85677809789); 15 var rc = times(3.1415926, 79.85677809789); 16 console.log(rc); 17 18 /** 19 * 把错误的数据转正 20 * strip(0.09999999999999998)=0.1 21 */ 22 function strip(num) { 23 var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 12; 24 25 return +parseFloat(num.toPrecision(precision)); 26 } 27 28 /** 29 * Return digits length of a number 30 * @param {*number} num Input number 31 */ 32 function digitLength(num) { 33 // Get digit length of e 34 var eSplit = num.toString().split(/[eE]/); 35 var len = (eSplit[0].split('.')[1] || '').length - +(eSplit[1] || 0); 36 return len > 0 ? len : 0; 37 } 38 39 /** 40 * 精确乘法 41 */ 42 function times(num1, num2) { 43 var num1Changed = Number(num1.toString().replace('.', '')); 44 var num2Changed = Number(num2.toString().replace('.', '')); 45 var baseNum = digitLength(num1) + digitLength(num2); 46 return num1Changed * num2Changed / Math.pow(10, baseNum); 47 } 48 49 /** 50 * 精确加法 51 */ 52 function plus(num1, num2) { 53 var baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2))); 54 return (times(num1, baseNum) + times(num2, baseNum)) / baseNum; 55 } 56 57 /** 58 * 精确减法 59 */ 60 function minus(num1, num2) { 61 var baseNum = Math.pow(10, Math.max(digitLength(num1), digitLength(num2))); 62 return (times(num1, baseNum) - times(num2, baseNum)) / baseNum; 63 } 64 65 /** 66 * 精确除法 67 */ 68 function divide(num1, num2) { 69 var num1Changed = Number(num1.toString().replace('.', '')); 70 var num2Changed = Number(num2.toString().replace('.', '')); 71 return times(num1Changed / num2Changed, Math.pow(10, digitLength(num2) - digitLength(num1))); 72 } 73 74 /** 75 * 四舍五入 76 */ 77 function round(num, ratio) { 78 var base = Math.pow(10, ratio); 79 return divide(Math.round(times(num, base)), base); 80 } 81 </script> 82 </head> 83 84 <body> 85 </body> 86 87 </html>