Skip to content

Commit

Permalink
Fix milliseconds rounding inconsistency (#41)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
  • Loading branch information
explodingcamera and sindresorhus authored Feb 12, 2020
1 parent 737628f commit f48b81c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
20 changes: 19 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,20 @@ module.exports = (milliseconds, options = {}) => {
}
}

// Round up milliseconds for values lager than 1 minute - 50ms since these
// always need to be round up.
// (this fixes issues when rounding seconds independently of minutes later)
if (
milliseconds >= (1000 * 60) - 50 &&
!options.separateMilliseconds &&
!options.formatSubMilliseconds
) {
const difference = 60 - (milliseconds % 60);
if (difference <= 50) {
milliseconds += difference;
}
}

const parsed = parseMilliseconds(milliseconds);

add(Math.trunc(parsed.days / 365), 'year', 'y');
Expand Down Expand Up @@ -84,9 +98,13 @@ module.exports = (milliseconds, options = {}) => {
options.millisecondsDecimalDigits :
0;

const roundedMiliseconds = millisecondsAndBelow >= 1 ?
Math.round(millisecondsAndBelow) :
Math.ceil(millisecondsAndBelow);

const millisecondsString = millisecondsDecimalDigits ?
millisecondsAndBelow.toFixed(millisecondsDecimalDigits) :
Math.ceil(millisecondsAndBelow);
roundedMiliseconds;

add(
parseFloat(millisecondsString, 10),
Expand Down
5 changes: 3 additions & 2 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ test('prettify milliseconds', t => {
t.is(prettyMilliseconds(1000 * 60 * 60 * 999), '41d 15h');
t.is(prettyMilliseconds(1000 * 60 * 60 * 24 * 465), '1y 100d');
t.is(prettyMilliseconds(1000 * 60 * 67 * 24 * 465), '1y 154d 6h');
t.is(prettyMilliseconds(119999), '2m');
});

test('have a compact option', t => {
Expand Down Expand Up @@ -43,8 +44,8 @@ test('have a secondsDecimalDigits option', t => {
});

test('have a millisecondsDecimalDigits option', t => {
t.is(prettyMilliseconds(33.333), '34ms');
t.is(prettyMilliseconds(33.333, {millisecondsDecimalDigits: 0}), '34ms');
t.is(prettyMilliseconds(33.333), '33ms');
t.is(prettyMilliseconds(33.333, {millisecondsDecimalDigits: 0}), '33ms');
t.is(prettyMilliseconds(33.333, {millisecondsDecimalDigits: 4}), '33.3330ms');
});

Expand Down

0 comments on commit f48b81c

Please sign in to comment.