subtract.js 779 B

12345678910111213141516171819202122232425
  1. var helperNumberDecimal = require('./helperNumberDecimal')
  2. var toNumberString = require('./toNumberString')
  3. var toNumber = require('./toNumber')
  4. var toFixed = require('./toFixed')
  5. /**
  6. * 减法运算
  7. *
  8. * @param { Number } num1 被减数
  9. * @param { Number } num2 减数
  10. * @return {Number}
  11. */
  12. function subtract (num1, num2) {
  13. var subtrahend = toNumber(num1)
  14. var minuend = toNumber(num2)
  15. var str1 = toNumberString(subtrahend)
  16. var str2 = toNumberString(minuend)
  17. var digit1 = helperNumberDecimal(str1)
  18. var digit2 = helperNumberDecimal(str2)
  19. var ratio = Math.pow(10, Math.max(digit1, digit2))
  20. var precision = (digit1 >= digit2) ? digit1 : digit2
  21. return parseFloat(toFixed((subtrahend * ratio - minuend * ratio) / ratio, precision))
  22. }
  23. module.exports = subtract