From 6ce9d30c0fbf9a2d4f0214610ff50b521ead0e30 Mon Sep 17 00:00:00 2001 From: Frank Stokes Date: Fri, 8 Oct 2021 11:19:50 +0200 Subject: [PATCH] Implement Symbol.toPrimitive --- decimal.js | 8 ++++++++ test/modules/toPrimitive.js | 23 +++++++++++++++++++++++ test/test.js | 3 ++- 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 test/modules/toPrimitive.js diff --git a/decimal.js b/decimal.js index aeb59dc..d2100c0 100644 --- a/decimal.js +++ b/decimal.js @@ -2467,6 +2467,14 @@ return x.isNeg() ? '-' + str : str; }; + /* + * The toPrimitive method is used when attempting to perform comparison operations. + * This implementation provides a sensible and user-expected implementation of how + * a Decimal should be transformed into a comparable number + */ + P[Symbol.toPrimitive] = function () { + return Number(this.toString()); + }; // Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers. diff --git a/test/modules/toPrimitive.js b/test/modules/toPrimitive.js new file mode 100644 index 0000000..bcd148f --- /dev/null +++ b/test/modules/toPrimitive.js @@ -0,0 +1,23 @@ +if (typeof T === 'undefined') require('../setup'); + +T('Symbol.toPrimitive', function () { + + function D(v) { return new Decimal(v); } + + Decimal.config({ + precision: 20, + rounding: 4, + toExpNeg: -9e15, + toExpPos: 9e15, + minE: -9e15, + maxE: 9e15 + }); + + T.assert(D('1') < D('2')); + T.assert(D('100') > D('2')); + T.assert(D('-435435.232') < D('2.09802')); + T.assert(D('-1.987234') > D('-2.5473421')); + T.assert(D('10.3') >= D('10.3')); + T.assert(D('10.3') <= D('10.3')); +}); + diff --git a/test/test.js b/test/test.js index 9758ea1..be1cc72 100644 --- a/test/test.js +++ b/test/test.js @@ -64,7 +64,8 @@ console.log('\n Testing decimal.js\n'); 'toSD', 'toString', 'trunc', - 'valueOf' + 'valueOf', + 'toPrimitive', ] .forEach(function (module) { require('./modules/' + module);