Skip to content

Commit

Permalink
Fix format size issue
Browse files Browse the repository at this point in the history
fix #147
  • Loading branch information
CzBiX committed Oct 7, 2022
1 parent 79e515a commit 21dc76b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/filters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@ import Vue from 'vue';

/* eslint-disable no-param-reassign */
export function toPrecision(value: number, precision: number) {
if (value >= (10 ** precision)) {
const limit = 10 ** precision;
if (value >= limit) {
return value.toString();
} if (value >= 1) {
}
if (value >= 1) {
if (value >= limit - 1) {
return limit.toString();
}

return value.toPrecision(precision);
}

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

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

while (value >= 1000) {
value = value / (1024 ** index);
if (value >= 999) {
value /= 1024;
index++;
}

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

if (index < 0) {
if (index === 0) {
return `${value} ${unit}`;
}

return `${toPrecision(value, 3)} ${unit}`;
}

Expand Down
4 changes: 4 additions & 0 deletions tests/unit/filters.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ describe('to precision', () => {
test.each([
[0.1, 1, '0'],
[0.1, 2, '0.1'],
[0.9, 1, '1'],
[99.5, 2, '100'],
[122, 1, '122'],
])('case %#', (value, precision, result) => {
expect(toPrecision(value, precision)).toEqual(result);
Expand All @@ -18,6 +20,8 @@ describe('format size', () => {
[0, '0 B'],
[10, '10 B'],
[500, '500 B'],
[998, '998 B'],
[999, '0.98 KiB'],
[1000, '0.98 KiB'],
])('case %#', (value, result) => {
expect(formatSize(value)).toEqual(result);
Expand Down

0 comments on commit 21dc76b

Please sign in to comment.