accuracy.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // var floatObj = function () {
  2. /*
  3. * 判断obj是否为一个整数
  4. */
  5. function isInteger(obj) {
  6. return Math.floor(obj) === obj
  7. }
  8. /*
  9. * 将一个浮点数转成整数,返回整数和倍数。如 3.14 >> 314,倍数是 100
  10. * @param floatNum {number} 小数
  11. * @return {object}
  12. * {times:100, num: 314}
  13. */
  14. function toInteger(floatNum) {
  15. var ret = {
  16. times: 1,
  17. num: 0
  18. };
  19. if (isInteger(floatNum)) {
  20. ret.num = floatNum;
  21. return ret
  22. }
  23. var strfi = floatNum + '';
  24. var dotPos = strfi.indexOf('.');
  25. var len = strfi.substr(dotPos + 1).length;
  26. var times = Math.pow(10, len);
  27. var intNum = parseInt(floatNum * times + 0.5, 10);
  28. ret.times = times;
  29. ret.num = intNum;
  30. return ret
  31. }
  32. /*
  33. * 核心方法,实现加减乘除运算,确保不丢失精度
  34. * 思路:把小数放大为整数(乘),进行算术运算,再缩小为小数(除)
  35. *
  36. * @param a {number} 运算数1
  37. * @param b {number} 运算数2
  38. * @param op {string} 运算类型,有加减乘除(add/subtract/multiply/divide)
  39. *
  40. */
  41. function operation(a, b, op) {
  42. let a1 = a < 0 ? Math.abs(a) : a;
  43. let b1 = b < 0 ? Math.abs(b) : b;
  44. var o1 = toInteger(a1);
  45. var o2 = toInteger(b1);
  46. var n1 = a < 0 ? -o1.num : o1.num;
  47. var n2 = b < 0 ? -o2.num : o2.num;
  48. var t1 = o1.times;
  49. var t2 = o2.times;
  50. var max = t1 > t2 ? t1 : t2;
  51. var result = null;
  52. switch (op) {
  53. case 'add':
  54. if (t1 === t2) { // 两个小数位数相同
  55. result = n1 + n2
  56. } else if (t1 > t2) { // o1 小数位 大于 o2
  57. result = n1 + n2 * (t1 / t2)
  58. } else { // o1 小数位 小于 o2
  59. result = n1 * (t2 / t1) + n2
  60. }
  61. return result / max;
  62. case 'subtract':
  63. if (t1 === t2) {
  64. result = n1 - n2
  65. } else if (t1 > t2) {
  66. result = n1 - n2 * (t1 / t2)
  67. } else {
  68. result = n1 * (t2 / t1) - n2
  69. }
  70. return result / max;
  71. case 'multiply':
  72. result = (n1 * n2) / (t1 * t2);
  73. return result;
  74. case 'divide':
  75. result = (n1 / n2) * (t2 / t1);
  76. return result
  77. }
  78. }
  79. // 加减乘除的四个接口
  80. export function add(a, b) {
  81. return operation(a, b, 'add')
  82. }
  83. export function subtract(a, b) {
  84. return operation(a, b, 'subtract')
  85. }
  86. export function multiply(a, b) {
  87. return operation(a, b, 'multiply')
  88. }
  89. export function divide(a, b) {
  90. return operation(a, b, 'divide')
  91. }
  92. // // exports
  93. // return {
  94. // add: add,
  95. // subtract: subtract,
  96. // multiply: multiply,
  97. // divide: divide
  98. // }
  99. // }()