Implement Symbol.toPrimitive

pull/186/head
Frank Stokes 3 years ago
parent 1bcf067429
commit 6ce9d30c0f

@ -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.

@ -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'));
});

@ -64,7 +64,8 @@ console.log('\n Testing decimal.js\n');
'toSD',
'toString',
'trunc',
'valueOf'
'valueOf',
'toPrimitive',
]
.forEach(function (module) {
require('./modules/' + module);

Loading…
Cancel
Save