Skip to content

Commit 21dc76b

Browse files
committedOct 7, 2022
Fix format size issue
fix #147
1 parent 79e515a commit 21dc76b

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed
 

‎src/filters.ts

+14-6
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,15 @@ import Vue from 'vue';
33

44
/* eslint-disable no-param-reassign */
55
export function toPrecision(value: number, precision: number) {
6-
if (value >= (10 ** precision)) {
6+
const limit = 10 ** precision;
7+
if (value >= limit) {
78
return value.toString();
8-
} if (value >= 1) {
9+
}
10+
if (value >= 1) {
11+
if (value >= limit - 1) {
12+
return limit.toString();
13+
}
14+
915
return value.toPrecision(precision);
1016
}
1117

@@ -14,18 +20,20 @@ export function toPrecision(value: number, precision: number) {
1420

1521
export function formatSize(value: number): string {
1622
const units = 'KMGTP';
17-
let index = -1;
23+
let index = value ? Math.floor(Math.log2(value) / 10) : 0;
1824

19-
while (value >= 1000) {
25+
value = value / (1024 ** index);
26+
if (value >= 999) {
2027
value /= 1024;
2128
index++;
2229
}
2330

24-
const unit = index < 0 ? 'B' : `${units[index]}iB`;
31+
const unit = index === 0 ? 'B' : `${units[index - 1]}iB`;
2532

26-
if (index < 0) {
33+
if (index === 0) {
2734
return `${value} ${unit}`;
2835
}
36+
2937
return `${toPrecision(value, 3)} ${unit}`;
3038
}
3139

‎tests/unit/filters.spec.ts

+4
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ describe('to precision', () => {
77
test.each([
88
[0.1, 1, '0'],
99
[0.1, 2, '0.1'],
10+
[0.9, 1, '1'],
11+
[99.5, 2, '100'],
1012
[122, 1, '122'],
1113
])('case %#', (value, precision, result) => {
1214
expect(toPrecision(value, precision)).toEqual(result);
@@ -18,6 +20,8 @@ describe('format size', () => {
1820
[0, '0 B'],
1921
[10, '10 B'],
2022
[500, '500 B'],
23+
[998, '998 B'],
24+
[999, '0.98 KiB'],
2125
[1000, '0.98 KiB'],
2226
])('case %#', (value, result) => {
2327
expect(formatSize(value)).toEqual(result);

0 commit comments

Comments
 (0)
Please sign in to comment.