Skip to content

Commit

Permalink
Added precision/digits option.
Browse files Browse the repository at this point in the history
  • Loading branch information
nmoinvaz committed Aug 30, 2020
1 parent 1000ebe commit 26c3b96
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
14 changes: 14 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ declare namespace prettyBytes {
```
*/
readonly binary?: boolean;

/**
Number of digits of precision to use calculating bytes or bits.
@default 3
```
import prettyBytes = require('pretty-bytes');
prettyBytes(1100, {digits: 2});
//=> '1.1 B'
```
*/
readonly digits?: number;
}
}

Expand Down
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ module.exports = (number, options) => {

const exponent = Math.min(Math.floor(options.binary ? Math.log(number) / Math.log(1024) : Math.log10(number) / 3), UNITS.length - 1);
// eslint-disable-next-line unicorn/prefer-exponentiation-operator
number = Number((number / Math.pow(options.binary ? 1024 : 1000, exponent)).toPrecision(3));
number = Number((number / Math.pow(options.binary ? 1024 : 1000, exponent)).toPrecision(options.digits || 3));
const numberString = toLocaleString(number, options.locale);

const unit = UNITS[exponent];
Expand Down
8 changes: 8 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,11 @@ test('binary option', t => {
t.is(prettyBytes(1e16, {binary: true}), '8.88 PB');
t.is(prettyBytes(1e30, {binary: true}), '827000 YB');
});

test('digits option', t => {
t.is(prettyBytes(1001), '1 kB');
t.is(prettyBytes(1001, {digits: 1}), '1 kB');
t.is(prettyBytes(1100, {digits: 2}), '1.1 kB');
t.is(prettyBytes(1010, {digits: 3}), '1.01 kB');
t.is(prettyBytes(1001, {digits: 4}), '1.001 kB');
});

0 comments on commit 26c3b96

Please sign in to comment.