Skip to content

Commit

Permalink
Fix {secDecimalDigits: 0} rounding rollover issue (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
kolyaventuri authored and sindresorhus committed Jul 18, 2018
1 parent ef7523b commit 7602f88
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
10 changes: 9 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ module.exports = (ms, options = {}) => {
ret.push((valueString || value) + postfix);
};

const secDecimalDigits = typeof options.secDecimalDigits === 'number' ? options.secDecimalDigits : 1;

if (secDecimalDigits < 1) {
const diff = 1000 - (ms % 1000);
if (diff < 500) {
ms += diff;
}
}

const parsed = parseMs(ms);

add(Math.trunc(parsed.days / 365), 'year', 'y');
Expand All @@ -38,7 +47,6 @@ module.exports = (ms, options = {}) => {
}

const sec = ms / 1000 % 60;
const secDecimalDigits = typeof options.secDecimalDigits === 'number' ? options.secDecimalDigits : 1;
const secFixed = sec.toFixed(secDecimalDigits);
const secStr = options.keepDecimalsOnWholeSeconds ? secFixed : secFixed.replace(/\.0+$/, '');
add(sec, 'second', 's', secStr);
Expand Down
9 changes: 9 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,12 @@ test('throw on invalid', t => {
m(Infinity);
});
});

test('properly rounds milliseconds with secDecimalDigits', t => {
const fn = ms => m(ms, {verbose: true, secDecimalDigits: 0});
t.is(fn(179700), '3 minutes');
t.is(fn((365 * 24 * 3600 * 1e3) - 1), '1 year');
t.is(fn((24 * 3600 * 1e3) - 1), '1 day');
t.is(fn((3600 * 1e3) - 1), '1 hour');
t.is(fn((2 * 3600 * 1e3) - 1), '2 hours');
});

0 comments on commit 7602f88

Please sign in to comment.