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:
parent
1bcf067429
commit
6ce9d30c0f
@ -2467,6 +2467,14 @@
|
|||||||
return x.isNeg() ? '-' + str : str;
|
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.
|
// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
|
||||||
|
|
||||||
|
23
test/modules/toPrimitive.js
Normal file
23
test/modules/toPrimitive.js
Normal 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'));
|
||||||
|
});
|
||||||
|
|
@ -64,7 +64,8 @@ console.log('\n Testing decimal.js\n');
|
|||||||
'toSD',
|
'toSD',
|
||||||
'toString',
|
'toString',
|
||||||
'trunc',
|
'trunc',
|
||||||
'valueOf'
|
'valueOf',
|
||||||
|
'toPrimitive',
|
||||||
]
|
]
|
||||||
.forEach(function (module) {
|
.forEach(function (module) {
|
||||||
require('./modules/' + module);
|
require('./modules/' + module);
|
||||||
|
Loading…
Reference in New Issue
Block a user