toNumberString.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. var helperStringRepeat = require('./helperStringRepeat')
  2. var helperNumberOffsetPoint = require('./helperNumberOffsetPoint')
  3. /**
  4. * 数值转字符串,科学计数转字符串
  5. * @param { Number } num 数值
  6. *
  7. * @return {Number}
  8. */
  9. function toNumberString(num) {
  10. var rest = '' + num
  11. var scienceMatchs = rest.match(/^([-+]?)((\d+)|((\d+)?[.](\d+)?))e([-+]{1})([0-9]+)$/)
  12. if (scienceMatchs) {
  13. var isNegative = num < 0
  14. var absFlag = isNegative ? '-' : ''
  15. var intNumStr = scienceMatchs[3] || ''
  16. var dIntNumStr = scienceMatchs[5] || ''
  17. var dFloatNumStr = scienceMatchs[6] || ''
  18. var sciencFlag = scienceMatchs[7]
  19. var scienceNumStr = scienceMatchs[8]
  20. var floatOffsetIndex = scienceNumStr - dFloatNumStr.length
  21. var intOffsetIndex = scienceNumStr - intNumStr.length
  22. var dIntOffsetIndex = scienceNumStr - dIntNumStr.length
  23. if (sciencFlag === '+') {
  24. if (intNumStr) {
  25. return absFlag + intNumStr + helperStringRepeat('0', scienceNumStr)
  26. }
  27. if (floatOffsetIndex > 0) {
  28. return absFlag + dIntNumStr + dFloatNumStr + helperStringRepeat('0', floatOffsetIndex)
  29. }
  30. return absFlag + dIntNumStr + helperNumberOffsetPoint(dFloatNumStr, scienceNumStr)
  31. }
  32. if (intNumStr) {
  33. if (intOffsetIndex > 0) {
  34. return absFlag + '0.' + helperStringRepeat('0', Math.abs(intOffsetIndex)) + intNumStr
  35. }
  36. return absFlag + helperNumberOffsetPoint(intNumStr, intOffsetIndex)
  37. }
  38. if (dIntOffsetIndex > 0) {
  39. return absFlag + '0.' + helperStringRepeat('0', Math.abs(dIntOffsetIndex)) + dIntNumStr + dFloatNumStr
  40. }
  41. return absFlag + helperNumberOffsetPoint(dIntNumStr, dIntOffsetIndex) + dFloatNumStr
  42. }
  43. return rest
  44. }
  45. module.exports = toNumberString