Decimal: Stage 1 Update (September, 2023)
Jesse Alama (Igalia, in partnership with Bloomberg)
Motivation
Use cases
There are both frontend and backend scenarios for the above.
Code samples
Get the total for a bill, after applying tax
function calculateBill(items, tax) {
let total = new Decimal("0");
for (let {price, count} of items) {
total = total.add(price.times(new Decimal(count)));
}
return total.multiply(new Decimal(tax).add(1));
}
let items = [{price: "1.25", count: 5}, {price: "5.00", count: 1}];
let tax = "0.0735";
console.log(calculateBill(items, tax).toFixed(2));
Amortization schedule for a loan
const principal = new Decimal("500000");
const annualInterestRate = new Decimal("0.05");
const paymentsPerYear = new Decimal("12");
const monthlyInterestRate = annualInterestRate.divide(paymentsPerYear);
const years = new Decimal("30");
const one = new Decimal("1");
const paymentCount = paymentsPerYear.times(years);
const monthlyPaymentAmount = principal.times(monthlyInterestRate)
.divide(one.minus(monthlyInterestRate).pow(paymentCount).minus(one))
.times(one.add(monthlyInterestRate));
Stepping up/down a value by a little bit
function stepUp(d, n, x) {
let increment = new Decimal("10").pow(x);
return d.add(n.times(increment));
}
let starting = new Decimal("1.23");
let stepped = stepUp(starting, new Decimal("3"), new Decimal("-4"));
console.log(stepped.toFixed(4)); // 1.2305
Connect to DB, use SQL DECIMAL type in JS
const { Client } = require('pg');
const client = new Client({
user: 'username',
sql_decimal: 'decimal128', // or 'string', 'number'
// ...more options
});
const boost = new Decimal("1.05");
client.query('SELECT prices FROM data_with_numbers', (err, res) => {
console.log(res.rows.map(row => row.prices.times(boost)));
client.end();
});
Changes to the proposal since last time
Keep, drop, add, open
Keep
Drop
Add
Open questions
Current shape of the proposal
But wait, there’s more! (…in the future, maybe)
Looking ahead to a potential v2 or v3 of Decimal, we can consider: