我想解析一个格式化的数字字符串,接受逗号空格、点作为千位分隔符以及逗号和点作为小数分隔符
示例 输入 = 1 2345,6 locale -swedish //输出 12345.6
输入 = 1.2345,6 -丹麦语 //输出 12345.6 输入 = 1,2345.6 - 英语 //输出 12345.6
这是解决您问题的示例解决方案。
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