toFixed.js 887 B

123456789101112131415161718192021222324252627282930
  1. var round = require('./round')
  2. var toValueString = require('./toValueString')
  3. var helperStringRepeat = require('./helperStringRepeat')
  4. var helperNumberOffsetPoint = require('./helperNumberOffsetPoint')
  5. /**
  6. * 将数值四舍五入并格式化为固定小数位的字符串
  7. *
  8. * @param {string|number} num 数值
  9. * @param {number} digits 小数保留位数
  10. * @return {String}
  11. */
  12. function toFixed (num, digits) {
  13. digits = digits >> 0
  14. var str = toValueString(round(num, digits))
  15. var nums = str.split('.')
  16. var intStr = nums[0]
  17. var floatStr = nums[1] || ''
  18. var digitOffsetIndex = digits - floatStr.length
  19. if (digits) {
  20. if (digitOffsetIndex > 0) {
  21. return intStr + '.' + floatStr + helperStringRepeat('0', digitOffsetIndex)
  22. }
  23. return intStr + helperNumberOffsetPoint(floatStr, Math.abs(digitOffsetIndex))
  24. }
  25. return intStr
  26. }
  27. module.exports = toFixed