context.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. const Decimal = require('decimal.js');
  3. const _ = require('lodash');
  4. // Decimal.set({ precision: 2 });
  5. module.exports = {
  6. turnDecimal(n) {
  7. if (_.isObject(n)) {
  8. n = JSON.parse(JSON.stringify(n));
  9. if (_.isObject(n)) n = _.get(n, '$numberDecimal');
  10. }
  11. return new Decimal(n);
  12. },
  13. // 加法
  14. plus(n1 = 0, n2 = 0) {
  15. const number1 = this.turnDecimal(n1);
  16. const number2 = this.turnDecimal(n2);
  17. const result = number1.add(number2).toFixed(2, Decimal.ROUND_DOWN);
  18. return this.toNumber(result);
  19. },
  20. // 减法
  21. minus(n1 = 0, n2 = 0) {
  22. const number1 = this.turnDecimal(n1);
  23. const number2 = this.turnDecimal(n2);
  24. const result = number1.minus(number2).toFixed(2, Decimal.ROUND_DOWN);
  25. return this.toNumber(result);
  26. },
  27. // 乘法
  28. multiply(n1 = 0, n2 = 0) {
  29. const number1 = this.turnDecimal(n1);
  30. const number2 = this.turnDecimal(n2);
  31. const result = number1.mul(number2).toFixed(2, Decimal.ROUND_DOWN);
  32. return this.toNumber(result);
  33. },
  34. // 除法
  35. divide(n1 = 0, n2 = 0) {
  36. const number1 = this.turnDecimal(n1);
  37. const number2 = this.turnDecimal(n2);
  38. const result = number1.div(number2).toFixed(2, Decimal.ROUND_DOWN);
  39. return this.toNumber(result);
  40. },
  41. toNumber(num) {
  42. if (_.isObject(num)) {
  43. num = JSON.parse(JSON.stringify(num));
  44. if (_.isObject(num)) num = _.get(num, '$numberDecimal');
  45. }
  46. return new Decimal(num).toNumber();
  47. },
  48. };