Decimal.js and JSON.stringify()

An example of how we can configure decimal.js to automatically round to the correct number of decimal places when JSON.stringify()-ed.

by ph822720355

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.0.0/decimal.min.js"></script>
<pre id="output"></pre>

JavaScript

var a = new Decimal(0.1);
var b = new Decimal(0.2);
var pi = new Decimal(Math.PI);

var myObj = {
    cost: a.plus(b),
    pi: pi,
    roundUp: new Decimal(1.005),
    roundDown: new Decimal(1.004),
    twentyNine: new Decimal(1.59264672 / 1.68)
};

// this causes all Decimals to be rounded
// to 2 decimal places whenever they are displayed
Decimal.prototype.toJSON = function(key) {
    return this.toNumber();
} 

const result = JSON.stringify(myObj, null, 4);

document.querySelector('#output').innerHTML = result;