Typescript: get number from string

Date: 2022-04-06
// the simple one
export const getNumber = (x: any, def: number): number => {
    if (typeof x === "number" && isFinite(x)) return x;
    if (!x) return def;
    if (typeof x === "string") return getNumber(Number(x), def);
    return def;
};

// for user input / display values
export function getNumberFromString(value: any) {
    const s = String(value).replace(/[^\d\.,-]/, "");
    const parts = s.split(/[\.,]/);
    if (parts.length > 1)
        parts.splice(parts.length - 1, 0, "."); // insert at index
    const j = parts.join("");
    return parseFloat(j) || 0.0;
}


const result = getNumberFromString("52.000,6");
console.log("result", result); // => 52000.6

// works with:
// 12345.56
// 12345,56
// 12,345.56
// 12.345,56
// 12.345.56 (results in the same, but is questionable)
// 12345..56 (results in the same, but is questionable)

export function currencyFormat(value: number, currencyISO: string = 'EUR') {
    if (typeof (value) !== "number" || Number.isNaN(value) || !Number.isFinite(value)) return "";
    const currencyFormatter = new Intl.NumberFormat('nl-NL', { style: 'currency', currency: currencyISO, minimumFractionDigits: 2, maximumFractionDigits: 6 });
    return currencyFormatter.format(value);
}





61080cookie-checkTypescript: get number from string