Matching Python’s Rounding With roundingMode
In this lesson, you ported the share on each café’s invoice line. The Python prints it with the
.0% format spec, {share:.0%}, and the line reads
Bluebell Café: 9.0 kg (12%), €172.80, RF3540422202610.
- The percent formatter, an
Intl.NumberFormatwithstyle: "percent", multiplies by 100, adds the percent sign, and rounds to a whole percent. Ported with it, Larder Lane’s50%and Northside’s38%match, but Bluebell’s line reads13%, with no error. - Bluebell’s share,
9 / 72, is exactly one eighth, and a double stores it exactly, so the share is12.5%on the dot: a half, equally close to12and13. - Python’s format specs round an exact half to the even digit, as
round()does:12%. The default rounding mode ofIntl.NumberFormat,"halfExpand", rounds a half away from zero:13%. Northside’s37.5%gives38%either way, because38is even. - Add
roundingMode: "halfEven"to the formatter’s options, and Bluebell’s line shows12%, as Python’s does.roundingModeis the formatter’s version ofrounding=inquantize(), with the opposite default: withoutrounding=,quantize()rounds a half to even. Five eighths,0.625, is63%by default and62%with"halfEven", as in Python. - The euro amounts need no change: whole cents never land on half a cent at two decimals.
- The other modes include
"trunc"(ROUND_DOWN),"ceil"(ROUND_CEILING) and"floor"(ROUND_FLOOR)."trunc"and"floor"also give12%for Bluebell, but37%for Northside."halfEven"is the one that rounds each exact half as Python does. .toFixed()rounds halves away from zero, like the formatter’s default:(12.5).toFixed(0)is"13". It has no option to change that, which is one more reason to format withIntl.NumberFormat.- One limit:
"halfEven"matches Python on exact halves. Both languages print0.545as0.545, but the double is a hair above the half. Python’s.0%rounds the stored value,55%, while the formatter rounds the printed0.545, an exact half to it,54%. - When a port must print what the Python printed, put the rounding rule in the formatter, once.
Every call then rounds exact halves as Python does; for values near a half, like
0.545, compare with Python’s output.
Here’s the share formatter on October’s three cafés, in grams:
const MONTH_GRAMS = 72000;
const cafeTotals = [
{ name: "Larder Lane", grams: 36000 },
{ name: "Bluebell Café", grams: 9000 },
{ name: "Northside Kitchen", grams: 27000 },
];
const percent = new Intl.NumberFormat("en-US", {
style: "percent",
roundingMode: "halfEven",
});
for (const cafe of cafeTotals) {
const share = cafe.grams / MONTH_GRAMS;
console.log(`${cafe.name}: ${percent.format(share)}`);
}
console.log(percent.format(0.625));