helpers.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /** Parse and print engineering notation */
  2. const prefixMap = {
  3. 1e-24: 'y',
  4. 1e-21: 'z',
  5. 1e-18: 'a',
  6. 1e-15: 'f',
  7. 1e-12: 'p',
  8. 1e-9: 'n',
  9. 1e-6: 'u',
  10. 1e-3: 'm',
  11. 1: '',
  12. 1e3: 'k',
  13. 1e6: 'M',
  14. 1e9: 'G',
  15. 1e12: 'T',
  16. 1e15: 'P',
  17. 1e18: 'E',
  18. 1e21: 'Z',
  19. 1e24: 'Y'
  20. }
  21. const REGEX_ENG = /^([+-])?\s*(\d*\.?\d+|\d+\.?\d*)?([yzafpnumkMGTPTEZY]|e[+-]?\d+)?$/
  22. export function printEng (number) {
  23. const factor = Object.keys(prefixMap).find((key) => {
  24. const ratio = Math.abs(number / key)
  25. return (ratio >= 1) && (ratio < 1000)
  26. })
  27. if (typeof factor !== 'undefined') {
  28. return (number / factor).toFixed(3).replace(/0+$/, '') + prefixMap[factor]
  29. } else {
  30. const base = Math.floor(Math.floor(Math.log10(Math.abs(number)) / 3))
  31. const value = (number / Math.pow(10, 3 * base)).toFixed(3).replace(/0+$/, '')
  32. return `${value}e${(3 * base).toFixed()}`
  33. }
  34. }
  35. export function parseEng (string) {
  36. const match = string.match(REGEX_ENG)
  37. if (!match) {
  38. return null
  39. }
  40. let num = 0
  41. let sign = 1
  42. let exp = 0
  43. if (match[1] === '-') {
  44. sign = -1
  45. }
  46. num = parseFloat(match[2])
  47. if (match[3] && match[3].length > 1) {
  48. exp = parseInt(match[3].substring(1))
  49. } else if (match[3]) {
  50. exp = prefixMap[match[3]]
  51. }
  52. return sign * num * Math.pow(10, exp)
  53. }