Skip to content
Open
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
18 changes: 18 additions & 0 deletions scripts/nutrition-import-numbers.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
5 changes: 4 additions & 1 deletion server/lib/nutrition-import/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(',', '.');
Expand Down