proposal-decimal
proposal-decimal copied to clipboard
Operations names (add/sub/div/mul) like in WebAssembly
Cmp() operator is used in sorting algorithms, but in math you usually want something like gte():
// current notation
if (a.cmp(b) == 1 || a.cmp(b) ==0) {
// do something
};
// proposed notation
if (a.gte(b)) {
// do something
}
Also names for basic operations add/sub/div/mul like in WebAssembly(Assembly) and in decimal.js is useful because it is much easier to write and read it. After some practice they feel like operator overloading +-/* and pretty readable.
let DEC = (x) => { new Decimal128(x) };
let costPrice = DEC('250'); // 250$
let profitPercent = DEC('30'); // 30%
//current notation
let sellPrice = profitPercent.add(DEC('100')).divide(DEC('100')).multiply(costPrice); //325$
//proposed notation
let sellPrice = profitPercent.add(DEC('100')).div(DEC('100')).mul(costPrice); //325$
End users can add DEC alias in context by hands if they need more compact expressions.
@yaffle also suggested the same syntax simplification ideas and even proposed further: the D128 or Dec128 class to the global context.
at the moment you'd do if (a.cmp(b) >= 0) {, which isn't that much worse than if (a.gte(b)) { (comparators don't have to return -1 or 1 for those cases, just any positive or negative number)
Awesome, even better.
In the latest version of the spec, the comparison operator cmp has been removed in favor of a lessThan and equals predicates. Does that address your concerns?
I'm not wedded to the names of the operators. Aligning things with WebAssembly is not a bad idea.
I don't think the WebAssembly names were really chosen with the goal of being an interface for application developers. I prefer the more explicit names, but also it's fine to iterate on this until the proposal is proposed for Stage 2.7.
Just to chime in with the status quo, as of today:
- We propose to use human-readable operation and comparison names ("multiply", "add", "lessThan", etc.) rather than the compact names used in WebAssembly and perhaps other languages.
- In earlier iterations of this proposal we used the name "cmp" but now use "compare".
@Yaffle also suggested the same syntax simplification ideas and even proposed further: the
D128orDec128class to the global context.
Thanks! The moderately longer name "Decimal128", while admittedly bulky, does align with the goal of making things human-readable. It also suggests to the programmer that we're dealing with decimal numbers, and are aligning with IEEE 754 Decimal128, which is a named standard thing that a web search will turn up. Although most programmers (I assume!) have never heard of Decimal128, this strikes me as a reasonable name for a standard library object.