喵喔喔
在现代浏览器中,您可以使用内置的Intl.NumberFormat来检测浏览器的数字格式并规范化输入以匹配。function parseNumber(value, locale = navigator.language) {
const example = Intl.NumberFormat(locale).format('1.1');
const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
const cleaned = value.replace(cleanPattern, '');
const normalized = cleaned.replace(example.charAt(1), '.');
return parseFloat(normalized);}const corpus = {
'1.123': {
expected: 1.123,
locale: 'en-US'
},
'1,123': {
expected: 1123,
locale: 'en-US'
},
'2.123': {
expected: 2123,
locale: 'fr-FR'
},
'2,123': {
expected: 2.123,
locale: 'fr-FR'
},}for (const candidate in corpus) {
const {
locale,
expected } = corpus[candidate];
const parsed = parseNumber(candidate, locale);
console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);}它们显然有一些优化和缓存的空间,但这在所有语言中都可靠地运行。