fix(helpers): Rework toPrecision (#1394)

This commit is contained in:
Rémi Marseault 2023-12-07 19:00:17 +01:00 committed by GitHub
parent a31a6435bf
commit 69398e02a5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 18 additions and 5 deletions

View file

@ -68,4 +68,7 @@ test('helpers/data/formatData', () => {
expect(formatData(1024, false)).toBe('1.02 kB')
expect(formatData(1024, true)).toBe('1.00 kiB')
expect(formatData(1052804121, true)).toBe('1004 MiB')
expect(formatData(1066436574, true)).toBe('1017 MiB')
})

View file

@ -11,6 +11,8 @@ test('helpers/number/toPrecision', () => {
expect(toPrecision(10, 2)).toBe('10')
expect(toPrecision(10, 1)).toBe('10')
expect(toPrecision(99.99, 3)).toBe('99.9')
expect(toPrecision(100, 3)).toBe('100')
})
@ -18,4 +20,6 @@ test('helpers/number/formatPercent', () => {
expect(formatPercent(0)).toBe('0.00 %')
expect(formatPercent(0.1)).toBe('10.0 %')
expect(formatPercent(1)).toBe('100 %')
expect(formatPercent(0.999942870757758)).toBe('99.9 %')
})

View file

@ -1,12 +1,18 @@
export function toPrecision(value: number, precision: number): string {
if (value >= 10 ** precision) {
return value.toString()
}
if (value >= 1) {
return value.toPrecision(precision)
return Math.floor(value).toString()
}
return value.toFixed(precision - 1)
const strValue = value.toFixed(precision)
if (strValue.length < Math.floor(Math.log10(value)) + 1) {
return strValue
} else {
const result = strValue.substring(0, precision + 1);
if (result.endsWith('.')) {
return result.slice(0, -1)
}
return result
}
}
export function formatPercent(progress: number): string {