calculate.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. // 加法
  2. function add(a, b) {
  3. const precision = Math.max(getPrecision(a), getPrecision(b));
  4. const multiplier = Math.pow(10, precision);
  5. return (multiply(a, multiplier) + multiply(b, multiplier)) / multiplier;
  6. }
  7. // 减法
  8. function subtract(a, b) {
  9. const precision = Math.max(getPrecision(a), getPrecision(b));
  10. const multiplier = Math.pow(10, precision);
  11. return (multiply(a, multiplier) - multiply(b, multiplier)) / multiplier;
  12. }
  13. // 乘法
  14. function multiply(a, b) {
  15. const precision = getPrecision(a) + getPrecision(b);
  16. const multiplier = Math.pow(10, precision);
  17. return Math.round(a * multiplier * b) / multiplier;
  18. }
  19. // 除法
  20. function divide(a, b) {
  21. const precision = Math.max(getPrecision(b), getPrecision(a));
  22. const divisor = Math.pow(10, precision);
  23. return (a * divisor) / (b * divisor);
  24. }
  25. // 获取浮点数的精度
  26. function getPrecision(num) {
  27. const str = num.toString();
  28. const decimalIndex = str.indexOf('.');
  29. return decimalIndex === -1 ? 0 : str.length - decimalIndex - 1;
  30. }
  31. export {
  32. add,
  33. subtract,
  34. multiply,
  35. divide
  36. }