Fix comma formatting bug in Grain.format (#2024)

Previously, Grain.format would output ",125,000g" rather than
"125,000g". Turned out to be an off-by-one issue when determining how
many commas to place. This commit fixes it, and I added a test case.

Test plan: `yarn test`
This commit is contained in:
Dandelion Mané 2020-07-22 21:02:39 -07:00 committed by GitHub
parent ece52200a0
commit e1886ff792
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 3 additions and 2 deletions

View File

@ -119,7 +119,7 @@ export function format(
// If we have more than 1000 grain, then we will insert commas for
// readability
const integerDigits = digits.length - DECIMAL_PRECISION;
const numCommasToInsert = Math.floor(integerDigits / 3);
const numCommasToInsert = Math.floor((integerDigits - 1) / 3);
for (let i = 0; i < numCommasToInsert; i++) {
// Count digits backwards from the last integer.
// Since we are moving from high index to low, we don't need to adjust for

View File

@ -14,11 +14,12 @@ describe("src/ledger/grain", () => {
expect(G.format(G.fromApproximateFloat(1.5))).toEqual("1g");
expect(G.format(G.fromApproximateFloat(42))).toEqual("42g");
});
it("correctly G.adds comma G.formatting for large numbers", () => {
it("correctly adds comma formatting for large numbers", () => {
expect(G.format(G.fromApproximateFloat(1337))).toEqual("1,337g");
expect(G.format(G.fromApproximateFloat(1337), 1)).toEqual("1,337.0g");
expect(G.format(G.fromApproximateFloat(1337.11))).toEqual("1,337g");
expect(G.format(G.fromApproximateFloat(1337.11), 1)).toEqual("1,337.1g");
expect(G.format(G.fromInteger(125000))).toEqual("125,000g");
expect(G.format(G.fromApproximateFloat(1337042.42), 0)).toEqual(
"1,337,042g"
);