1
0
mirror of https://github.com/MikeMcl/decimal.js.git synced 2024-10-27 20:34:12 +00:00

Implement Symbol.toPrimitive

This commit is contained in:
Frank Stokes 2021-10-08 11:19:50 +02:00
parent 1bcf067429
commit 6ce9d30c0f
3 changed files with 33 additions and 1 deletions

View File

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

View File

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

View File

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