Extract code about value formats from grafana repo and did some slight changes.
$ npm install @baurine/grafana-value-formats
// or
$ yarn add @baurine/grafana-value-formats
(I publish this package to npm registry and GitHub Packages both.)
The main function is function getValueFormat(unitFormat: string): string {...}
, it will return a function whose signature is below:
export type ValueFormatter = (
value: number,
decimals?: DecimalCount,
scaledDecimals?: DecimalCount,
isUtc?: boolean
) => string
Samples: (copy from valueForamts.test.ts)
// if scaledDecimals is null, use decimals
const str = getValueFormat('ms')(10000086.123, 0, null)
expect(str).toBe('3 hour')
const str = getValueFormat('ms')(10000086.123, 1, null)
expect(str).toBe('2.8 hour')
const str = getValueFormat('kbytes')(10000000, 3, null)
expect(str).toBe('9.537 GiB')
const str = getValueFormat('deckbytes')(10000000, 3, null)
expect(str).toBe('10.000 GB')
// if scaledDecimals is not null, use scaledDecimals, ignore decimals
const str = getValueFormat('ms')(1200, 0, 0)
expect(str).toBe('1.200 s')
You can find all unitFormat
we can use in the categories.ts
, or exported getValueFormats()
function.
- Add IEC units for Data rate
- Update id of Data rate in SI units
- Use dayjs to replace momentjs
- Nothing changes, just bump version
- Add "qps" unit (#4)
-
Change a part implementation of
scaledUnits()
method insrc/valueFormats/valueFormats.ts
line 126:if (steps > 0 && scaledDecimals !== null && scaledDecimals !== undefined) { // old logic // decimals = scaledDecimals + 3 * steps; // 为什么是乘以 3,大概是以 factor = 1000 为准,1000 表示 3 个小数点 // current logic // related issue: https://github.com/grafana/grafana/issues/23561 decimals = scaledDecimals }
So at before
expect(scaler(98765, 0, 2)).toBe('98.76500K') // because the decimals = 1*3 + 2
and now
expect(scaler(98765, 0, 2)).toBe('98.77K') // because the decimals = 2