Skip to content

Commit

Permalink
fix: sub-second precisions need to be rounded at the seconds field to…
Browse files Browse the repository at this point in the history
… avoid adding floats (#2377)
  • Loading branch information
creedasaurus authored Jul 27, 2023
1 parent 5f3f878 commit a9d7d03
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/plugin/duration/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ class Duration {

let seconds = this.$d.seconds || 0
if (this.$d.milliseconds) {
seconds += Math.round(this.$d.milliseconds) / 1000
seconds += this.$d.milliseconds / 1000
seconds = Math.round(seconds * 1000) / 1000
}

const S = getNumberUnitFormat(seconds, 'S')
Expand Down
9 changes: 9 additions & 0 deletions test/plugin/duration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,15 @@ describe('Creating', () => {
expect(dayjs.duration(1000.5).toISOString()).toBe('PT1.001S')
expect(dayjs.duration(-1000.5).toISOString()).toBe('-PT1S')
})
it('should handle floating point rounding errors', () => {
// An example of this is when adding 2 to 0.812 seconds, which is how
// the seconds component is calculated in .toISOString().
// > 2 + 0.812
// 2.8120000000000003
expect(dayjs.duration(-2812).toISOString()).toBe('-PT2.812S') // was -PT2.8120000000000003S
expect(dayjs.duration(3121632.27382247).toISOString()).toBe('PT52M1.632S') // was PT52M1.6320000000000001S
expect(dayjs.duration(7647826.525774224).toISOString()).toBe('PT2H7M27.827S') // was PT2H7M27.826999999999998S
})
})

describe('Parse ISO string', () => {
Expand Down

0 comments on commit a9d7d03

Please sign in to comment.