Files
fredy/lib/utils/extract-number.js

20 lines
645 B
JavaScript
Raw Permalink Normal View History

/*
* Copyright (c) 2026 by Christian Kellner.
* Licensed under Apache-2.0 with Commons Clause and Attribution/Naming Clause
*/
/**
* Extract the first number from a string like "1.234 €" or "70 m²".
2026-06-13 14:02:42 +02:00
* Removes dots/commas before parsing. Returns null when the input is
* null/undefined or cannot be parsed into a number.
* @param {string|undefined|null} str
* @returns {number|null}
*/
export const extractNumber = (str) => {
2026-06-13 14:02:42 +02:00
if (str == null) return null;
if (typeof str === 'number') return str;
const cleaned = str.replace(/\./g, '').replace(',', '.');
const num = parseFloat(cleaned);
return isNaN(num) ? null : num;
};