Skip to content

Commit

Permalink
Add signed option (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
Turbo87 authored and sindresorhus committed Jun 7, 2018
1 parent 11b08e0 commit 10fbba2
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 2 deletions.
9 changes: 7 additions & 2 deletions index.js
Expand Up @@ -36,15 +36,20 @@ module.exports = (number, options) => {

options = Object.assign({}, options);

if (options.signed && number === 0) {
return ' 0 B';
}

const isNegative = number < 0;
const prefix = isNegative ? '-' : (options.signed ? '+' : '');

if (isNegative) {
number = -number;
}

if (number < 1) {
const numberString = toLocaleString(number, options.locale);
return (isNegative ? '-' : '') + numberString + ' B';
return prefix + numberString + ' B';
}

const exponent = Math.min(Math.floor(Math.log10(number) / 3), UNITS.length - 1);
Expand All @@ -53,5 +58,5 @@ module.exports = (number, options) => {

const unit = UNITS[exponent];

return (isNegative ? '-' : '') + numberString + ' ' + unit;
return prefix + numberString + ' ' + unit;
};
12 changes: 12 additions & 0 deletions readme.md
Expand Up @@ -26,6 +26,10 @@ prettyBytes(1337);
prettyBytes(100);
//=> '100 B'

// Display file size differences
prettyBytes(42, {signed: true});
//=> '+42 B'

// Localized output using German locale
prettyBytes(1337, {locale: 'de'});
//=> '1,34 kB'
Expand All @@ -46,6 +50,14 @@ The number to format.

Type: `Object`

##### signed

Type: `boolean`<br>
Default: `false`

Include plus sign for positive numbers. If the difference is exactly zero a space character will be prepended instead for better alignment.


##### locale

Type: `boolean` `string`<br>
Expand Down
6 changes: 6 additions & 0 deletions test.js
Expand Up @@ -63,3 +63,9 @@ test('locale option', t => {
t.is(m(10.1, {locale: undefined}), '10.1 B');
t.is(m(1e30, {locale: undefined}), '1000000 YB');
});

test('signed option', t => {
t.is(m(42, {signed: true}), '+42 B');
t.is(m(-13, {signed: true}), '-13 B');
t.is(m(0, {signed: true}), ' 0 B');
});

0 comments on commit 10fbba2

Please sign in to comment.