如何在Javascript中根据本地区域设置解析格式化的Number()

问题描述 投票:0回答:1

我想解析一个格式化的数字字符串,接受逗号空格、点作为千位分隔符以及逗号和点作为小数分隔符

示例 输入 = 1 2345,6 locale -swedish //输出 12345.6

输入 = 1.2345,6 -丹麦语 //输出 12345.6 输入 = 1,2345.6 - 英语 //输出 12345.6

javascript reactjs arrays parsing number-systems
1个回答
0
投票

这是解决您问题的示例解决方案。

function parseFormattedNumber(inputStr, locale) {
    let thousandSeparator, decimalSeparator;

    // Define locale-specific separators
    switch (locale) {
        case "swedish":
            thousandSeparator = /[,. ]/;
            decimalSeparator = /[,.]/;
            break;
        case "danish":
            thousandSeparator = /[,.]/;
            decimalSeparator = /[,.]/;
            break;
        case "english":
            thousandSeparator = /[, ]/;
            decimalSeparator = /[,.]/;
            break;
        default:
            throw new Error("Unsupported locale");
    }

    // Remove thousand separators and replace decimal separator with dot
    const cleanedStr = inputStr.replace(thousandSeparator, "").replace(decimalSeparator, ".");

    // Convert the string to a float
    const result = parseFloat(cleanedStr);

    return result;
}

// Examples
console.log(parseFormattedNumber("1 2345,6", "swedish"));  // Output: 12345.6
console.log(parseFormattedNumber("1.2345,6", "danish"));   // Output: 12345.6
console.log(parseFormattedNumber("1,2345.6", "english"));  // Output: 12345.6

© www.soinside.com 2019 - 2024. All rights reserved.