Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix floating point comparison errors #16

Merged
merged 2 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions src/Converters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ import {v4 as uuidv4} from 'uuid';
import * as ynab from 'ynab';

import {getAmazonOrderLabelElements} from './AmazonLinks';
import {
areEqualWithPrecision,
HARDCODED_CURRENCY_DECIMAL_DIGITS,
parseLocaleNumber,
} from './Currency';
import {getDateString} from './DateUtils';
import isNonNullable from './isNonNullable';
import {ON_TRUNCATE_TYPES} from './LabelElements';
Expand All @@ -15,7 +20,6 @@ import {
type StandardTransactionTypeWithLabelElements,
type YnabCsvTransactionType,
} from './LabelTypes';
import parseLocaleNumber from './parseLocaleNumber';

type DateCandidateWithPosition = {
date: Date;
Expand Down Expand Up @@ -248,6 +252,7 @@ export function getLabelsFromAmazonOrders(
(transaction) => transaction.amount != null && transaction.date != null,
) as TransactionDataNonNullable[];

// NOTE: This can lead to floating point numbers like 54.68000000000001, so it's imperative here that we handle that down below when we compare this to the parsed order total
const transactionDataTotal = transactionData.reduce(
(acc, curr) => acc + (curr.amount ?? 0),
0,
Expand Down Expand Up @@ -280,10 +285,16 @@ export function getLabelsFromAmazonOrders(
return orderLabel;
}

if (transactionDataTotal !== parsedOrderTotal) {
console.debug(
if (
!areEqualWithPrecision(
transactionDataTotal,
parsedOrderTotal,
HARDCODED_CURRENCY_DECIMAL_DIGITS,
)
) {
console.warn(
'[getLabelsFromAmazonOrders] transaction data from order did not add up to order total. Bailing on using transaction data.',
{parsedOrderTotal, transactionData},
{parsedOrderTotal, transactionData, transactionDataTotal},
);
return orderLabel;
}
Expand Down
55 changes: 55 additions & 0 deletions src/Currency.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Currency.test.ts
import {areEqualWithPrecision} from './Currency';

describe('areEqualWithPrecision', () => {
test('should return true for numbers that are equal with the specified precision', () => {
expect(areEqualWithPrecision(1.12343, 1.12344, 4)).toBe(true);
expect(areEqualWithPrecision(1.12345, 1.12345, 5)).toBe(true);
expect(areEqualWithPrecision(123.456, 123.456, 3)).toBe(true);
});

test('should return false for numbers that are not equal with the specified precision', () => {
expect(areEqualWithPrecision(1.12345, 1.12344, 5)).toBe(false);
expect(areEqualWithPrecision(1.12345, 1.12346, 5)).toBe(false);
expect(areEqualWithPrecision(123.456, 123.457, 3)).toBe(false);
});

test('should handle very small numbers correctly', () => {
expect(areEqualWithPrecision(0.00000123, 0.00000124, 7)).toBe(true);
expect(areEqualWithPrecision(0.00000123, 0.00000125, 7)).toBe(false);
});

test('should handle very large numbers correctly', () => {
expect(areEqualWithPrecision(123456789.12345, 123456789.12344, 4)).toBe(
true,
);
expect(areEqualWithPrecision(123456789.12345, 123456789.12346, 5)).toBe(
false,
);
});

test('should handle different values for the digits parameter', () => {
expect(areEqualWithPrecision(1.1112, 1.1113, 3)).toBe(true);
expect(areEqualWithPrecision(1.1112, 1.1113, 4)).toBe(false);

expect(areEqualWithPrecision(1.11112, 1.11113, 4)).toBe(true);
expect(areEqualWithPrecision(1.11112, 1.11113, 5)).toBe(false);
});

test('rounds predictably', () => {
expect(areEqualWithPrecision(5.123, 5.125, 2)).toBe(false);
expect(areEqualWithPrecision(5.123, 5.124, 2)).toBe(true);
});

test('handles a real-life scenario as expected', () => {
const itemsTotal = 5 + 2.26 + 80.51; // 87.77000000000001
const expectedTotal = 87.77;

expect(itemsTotal).not.toStrictEqual(expectedTotal);
expect(areEqualWithPrecision(itemsTotal, expectedTotal, 2)).toBe(true);
});

test('throws if a negative number is passed for digits', () => {
expect(() => areEqualWithPrecision(1, 1, -2)).toThrow();
});
});
41 changes: 33 additions & 8 deletions src/parseLocaleNumber.ts → src/Currency.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
/**
* Parse a localized number to a float.
* From: https://stackoverflow.com/a/29273131/18265617
*
* @param {string} stringNumber - the localized number
* @param {string} locale - [optional] the locale that the number is represented in. Omit this parameter to use the current locale.
*/
// TODO: Figure out the best way to support other locales/currencies
const HARDCODED_LOCALE = 'en-US';
const HARDCODED_CURRENCY = 'USD';

// TODO: Don't hardcode decimal digits
export const HARDCODED_CURRENCY_DECIMAL_DIGITS = 2;

const CURRENCY_SYMBOL_FALLBACK = '$';
const CURRENCY_SYMBOL =
new Intl.NumberFormat(HARDCODED_LOCALE, {
Expand All @@ -17,7 +14,14 @@ const CURRENCY_SYMBOL =
?.formatToParts(1)
?.find((x) => x.type === 'currency')?.value ?? CURRENCY_SYMBOL_FALLBACK;

export default function parseLocaleNumber(
/**
* Parse a localized number to a float.
* From: https://stackoverflow.com/a/29273131/18265617
*
* @param {string} stringNumber - the localized number
* @param {string} locale - [optional] the locale that the number is represented in. Omit this parameter to use the current locale.
*/
export function parseLocaleNumber(
stringNumber: string,
locale?: string,
): number {
Expand All @@ -35,3 +39,24 @@ export default function parseLocaleNumber(
.replace(new RegExp('\\' + decimalSeparator), '.'),
);
}

/**
* NOTE: I did a lot of research on how to best do this, and didn't find a clear winning
* solution or library. So this is a best effort for now. Probably want to revisit this.
*
* Resources:
* https://stackoverflow.com/questions/2876536/precise-financial-calculation-in-javascript-what-are-the-gotchas
* https://medium.com/@magnusjt/how-to-handle-money-in-javascript-b954d612373c
*
* @param n1
* @param n2
* @param digits
* @returns
*/
export function areEqualWithPrecision(
n1: number,
n2: number,
digits: number,
): boolean {
return n1.toFixed(digits) === n2.toFixed(digits);
}
Loading