12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- /** Parse and print engineering notation */
- const prefixMap = {
- 1e-24: 'y',
- 1e-21: 'z',
- 1e-18: 'a',
- 1e-15: 'f',
- 1e-12: 'p',
- 1e-9: 'n',
- 1e-6: 'u',
- 1e-3: 'm',
- 1: '',
- 1e3: 'k',
- 1e6: 'M',
- 1e9: 'G',
- 1e12: 'T',
- 1e15: 'P',
- 1e18: 'E',
- 1e21: 'Z',
- 1e24: 'Y'
- }
- const REGEX_ENG = /^([+-])?\s*(\d*\.?\d+|\d+\.?\d*)?([yzafpnumkMGTPTEZY]|e[+-]?\d+)?$/
- export function printEng (number) {
- const factor = Object.keys(prefixMap).find((key) => {
- const ratio = Math.abs(number / key)
- return (ratio >= 1) && (ratio < 1000)
- })
- if (typeof factor !== 'undefined') {
- return (number / factor).toFixed(3).replace(/0+$/, '') + prefixMap[factor]
- } else {
- const base = Math.floor(Math.floor(Math.log10(Math.abs(number)) / 3))
- const value = (number / Math.pow(10, 3 * base)).toFixed(3).replace(/0+$/, '')
- return `${value}e${(3 * base).toFixed()}`
- }
- }
- export function parseEng (string) {
- const match = string.match(REGEX_ENG)
- if (!match) {
- return null
- }
- let num = 0
- let sign = 1
- let exp = 0
- if (match[1] === '-') {
- sign = -1
- }
- num = parseFloat(match[2])
- if (match[3] && match[3].length > 1) {
- exp = parseInt(match[3].substring(1))
- } else if (match[3]) {
- exp = prefixMap[match[3]]
- }
- return sign * num * Math.pow(10, exp)
- }
|