commafy.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var round = require('./round')
  2. var ceil = require('./ceil')
  3. var floor = require('./floor')
  4. var isNumber = require('./isNumber')
  5. var toValueString = require('./toValueString')
  6. var toFixed = require('./toFixed')
  7. var toNumberString = require('./toNumberString')
  8. /**
  9. * 千分位分隔符、小数点
  10. *
  11. * @param {String/Number} num 数值
  12. * @param {CommafyOptions} options 参数
  13. * @return {String}
  14. */
  15. function commafy(num, options) {
  16. var opts = options || {}
  17. var optDigits = opts.digits
  18. var isNum = isNumber(num)
  19. var rest, result, isNegative, intStr, floatStr
  20. if (isNum) {
  21. rest = (opts.ceil ? ceil : (opts.floor ? floor : round))(num, optDigits)
  22. result = toNumberString(optDigits ? toFixed(rest, optDigits) : rest).split('.')
  23. intStr = result[0]
  24. floatStr = result[1]
  25. isNegative = intStr && rest < 0
  26. if (isNegative) {
  27. intStr = intStr.substring(1, intStr.length)
  28. }
  29. } else {
  30. rest = toValueString(num).replace(/,/g, '')
  31. result = rest ? [rest] : []
  32. intStr = result[0]
  33. }
  34. if (result.length) {
  35. return (isNegative ? '-' : '') + intStr.replace(new RegExp('(?=(?!(\\b))(.{' + (opts.spaceNumber || 3) + '})+$)', 'g'), (opts.separator || ',')) + (floatStr ? ('.' + floatStr) : '')
  36. }
  37. return rest
  38. }
  39. module.exports = commafy