math.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. module.exports = {
  2. /**
  3. * +
  4. * @param arg1
  5. * @param arg2
  6. * @returns {number}
  7. */
  8. add: function(arg1, arg2) {
  9. var r1, r2, m;
  10. try {
  11. r1 = arg1.toString().split(".")[1].length
  12. } catch (e) {
  13. r1 = 0
  14. }
  15. try {
  16. r2 = arg2.toString().split(".")[1].length
  17. } catch (e) {
  18. r2 = 0
  19. }
  20. m = Math.pow(10, Math.max(r1, r2))
  21. return (arg1 * m + arg2 * m) / m
  22. },
  23. /**
  24. * -
  25. * @param arg1
  26. * @param arg2
  27. * @returns {number}
  28. */
  29. sub: function(arg1, arg2) {
  30. var r1, r2, m, n;
  31. try {
  32. r1 = arg1.toString().split(".")[1].length
  33. } catch (e) {
  34. r1 = 0
  35. }
  36. try {
  37. r2 = arg2.toString().split(".")[1].length
  38. } catch (e) {
  39. r2 = 0
  40. }
  41. m = Math.pow(10, Math.max(r1, r2));
  42. n = (r1 >= r2) ? r1 : r2;
  43. return ((arg1 * m - arg2 * m) / m).toFixed(n);
  44. },
  45. /**
  46. * *
  47. * @param arg1
  48. * @param arg2
  49. * @returns {number}
  50. */
  51. mul: function(arg1, arg2) {
  52. var m = 0,
  53. s1 = arg1.toString(),
  54. s2 = arg2.toString();
  55. try {
  56. m += s1.split(".")[1].length
  57. } catch (e) {}
  58. try {
  59. m += s2.split(".")[1].length
  60. } catch (e) {}
  61. return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
  62. },
  63. /**
  64. * /
  65. * @param arg1
  66. * @param arg2
  67. * @returns {number}
  68. */
  69. div: function(arg1, arg2) {
  70. var t1 = 0,
  71. t2 = 0,
  72. r1, r2;
  73. try {
  74. t1 = arg1.toString().split(".")[1].length
  75. } catch (e) {}
  76. try {
  77. t2 = arg2.toString().split(".")[1].length
  78. } catch (e) {}
  79. r1 = Number(arg1.toString().replace(".", ""))
  80. r2 = Number(arg2.toString().replace(".", ""))
  81. return this.mul((r1 / r2), Math.pow(10, t2 - t1));
  82. },
  83. /**
  84. * 保留有效小数位 四舍五入,解决toFixed方法bug
  85. * @param num 需要操作的数字
  86. * @param decimal 保留小数的位数
  87. * @returns {string}
  88. */
  89. toFixed: function(num, decimal) {
  90. if(typeof decimal == 'undefined'){
  91. decimal = 2;
  92. }
  93. var times = Math.pow(10, decimal)
  94. var des = num * times + 0.5
  95. des = (parseInt(des, 10) / times).toString()
  96. if(decimal > 0){
  97. var arr = des.split('.')
  98. var len = decimal;
  99. if(arr.length == 1){
  100. des += '.';
  101. }else{
  102. len = decimal - arr[1].length;
  103. }
  104. for (let i = 1; i <= len; i++) {
  105. des += '0';
  106. }
  107. }
  108. return des;
  109. },
  110. };