Skip to content

Commit

Permalink
Fix for negative units in conversions
Browse files Browse the repository at this point in the history
Closes #1482
  • Loading branch information
icambron committed Aug 22, 2023
1 parent 559a212 commit 11e454c
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
7 changes: 4 additions & 3 deletions src/duration.js
Expand Up @@ -10,6 +10,7 @@ import {
isUndefined,
normalizeObject,
roundTo,
signedFloor,
} from "./impl/util.js";
import Settings from "./settings.js";
import DateTime from "./datetime.js";
Expand Down Expand Up @@ -133,9 +134,9 @@ function removePrecisionIssue(a) {

// NB: mutates parameters
function convert(matrix, fromMap, fromUnit, toMap, toUnit) {
const conv = matrix[toUnit][fromUnit],
raw = fromMap[fromUnit] / conv,
added = Math.floor(raw);
const conv = matrix[toUnit][fromUnit];
const raw = fromMap[fromUnit] / conv;
const added = signedFloor(raw);

toMap[toUnit] = removePrecisionIssue(toMap[toUnit] + added);
fromMap[fromUnit] = removePrecisionIssue(fromMap[fromUnit] - added * conv);
Expand Down
4 changes: 4 additions & 0 deletions src/impl/util.js
Expand Up @@ -124,6 +124,10 @@ export function parseMillis(fraction) {
}
}

export function signedFloor(number) {
return number > 0 ? Math.floor(number) : Math.ceil(number);
}

export function roundTo(number, digits, towardZero = false) {
const factor = 10 ** digits,
rounder = towardZero ? Math.trunc : Math.round;
Expand Down
9 changes: 9 additions & 0 deletions test/duration/units.test.js
Expand Up @@ -96,6 +96,15 @@ test("Duration#shiftTo boils hours down to hours and minutes", () => {
});
});

test("Duration#shiftTo handles mixed units", () => {
const dur = Duration.fromObject({ weeks: -1, days: 14 });
expect(dur.shiftTo("years", "months", "weeks").toObject()).toEqual({
years: 0,
months: 0,
weeks: 1,
});
});

//------
// #shiftToAll()
//-------
Expand Down

0 comments on commit 11e454c

Please sign in to comment.