diff --git a/scripts/nutrition-import-numbers.test.js b/scripts/nutrition-import-numbers.test.js new file mode 100644 index 00000000..e73b3795 --- /dev/null +++ b/scripts/nutrition-import-numbers.test.js @@ -0,0 +1,18 @@ +/** + * Spreadsheet exports keep the displayed value, so a column with a thousands + * format writes "1,150". That is 1150, not 1.15; "1,5" stays a decimal comma. + */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { parseNumber } from '../server/lib/nutrition-import/common.js'; + +test('a comma before groups of three digits separates thousands', () => { + assert.equal(parseNumber('1,150'), 1150); + assert.equal(parseNumber('12,000'), 12000); + assert.equal(parseNumber('1,250.5'), 1250.5); +}); + +test('a lone comma with one or two decimals is a decimal comma', () => { + assert.equal(parseNumber('1,5'), 1.5); + assert.equal(parseNumber('12,25'), 12.25); +}); diff --git a/server/lib/nutrition-import/common.js b/server/lib/nutrition-import/common.js index bbcbe784..2d1eed5b 100644 --- a/server/lib/nutrition-import/common.js +++ b/server/lib/nutrition-import/common.js @@ -257,7 +257,10 @@ export function parseNumber(s) { // Handle "1,5" but NOT "1,500" (thousands separator). If there's exactly one // comma and no period, treat comma as decimal. let normalized = str; - if (normalized.includes(',') && !normalized.includes('.')) { + if (/^[+-]?\d{1,3}(,\d{3})+(\.\d+)?$/.test(normalized)) { + // "1,150", "12,000", "1,250.5": commas group thousands + normalized = normalized.replace(/,/g, ''); + } else if (normalized.includes(',') && !normalized.includes('.')) { const commas = normalized.split(',').length - 1; if (commas === 1 && /^\d+,\d+/.test(normalized)) { normalized = normalized.replace(',', '.');