Skip to content

Commit

Permalink
fix: remove floating point rounding error in Timestamp.fromMillis() (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
Brian Chen committed Apr 7, 2021
1 parent 42ade78 commit 97e7281
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
4 changes: 3 additions & 1 deletion dev/src/timestamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,9 @@ export class Timestamp implements firestore.Timestamp {
*/
static fromMillis(milliseconds: number): Timestamp {
const seconds = Math.floor(milliseconds / 1000);
const nanos = (milliseconds - seconds * 1000) * MS_TO_NANOS;
const nanos = Math.floor(
milliseconds * MS_TO_NANOS - seconds * 1000 * MS_TO_NANOS
);
return new Timestamp(seconds, nanos);
}

Expand Down
6 changes: 6 additions & 0 deletions dev/test/timestamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ describe('timestamps', () => {
expect(actual.isEqual(expected)).to.be.true;
});

it('handles decimal inputs in fromMillis()', () => {
const actual = Firestore.Timestamp.fromMillis(1000.1);
const expected = new Firestore.Timestamp(1, 100000);
expect(actual.isEqual(expected)).to.be.true;
});

it('validates seconds', () => {
expect(() => new Firestore.Timestamp(0.1, 0)).to.throw(
'Value for argument "seconds" is not a valid integer.'
Expand Down

0 comments on commit 97e7281

Please sign in to comment.