base_calc.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const mulPrecision = 12, divPrecision = 12;
  10. function digitLength (num) {
  11. // 兼容科学计数
  12. var eSplit = num.toString().split(/[eE]/);
  13. var len = (eSplit[0].split('.')[1] || '').length - (+(eSplit[1] || 0));
  14. return len > 0 ? len : 0;
  15. }
  16. function powLength (num) {
  17. var rs = num.toString();
  18. if (rs.indexOf('+') > 0) {
  19. return rs.match(/0*$/g).length();
  20. } else {
  21. const eSplit = rs.split(/[eE]/);
  22. const len = Number(eSplit[1]) - this.digitLength(eSplit[0]);
  23. return len > 0 ? len : 0;
  24. }
  25. }
  26. function round (num, digit) {
  27. return Math.round(num * Math.pow(10, digit)) / Math.pow(10, digit);
  28. }
  29. function add(num1, num2) {
  30. var d1 = this.digitLength(num1), d2 = this.digitLength(num2);
  31. return this.round(num1 + num2, Math.max(d1, d2));
  32. }
  33. function sub(num1, num2) {
  34. var d1 = this.digitLength(num1), d2 = this.digitLength(num2);
  35. return this.round(num1 - num2, Math.max(d1, d2));
  36. }
  37. function mul(num1, num2) {
  38. return this.round(num1 * num2, mulPrecision);
  39. }
  40. function div(num1, num2) {
  41. return this.round(num1 / num2, divPrecision);
  42. }
  43. module.exports = {
  44. digitLength: digitLength,
  45. powLength: powLength,
  46. round: round,
  47. add: add,
  48. sub: sub,
  49. mul: mul,
  50. div: div,
  51. };