如何允许德语用户在 React 中输入德语格式的数字 JavaScript
How to allow german user to enter numbers in german format in React JavaScript
我们正在开发应同时支持德语和英语用户的应用程序。
我们可以做些什么来让德国用户以德语格式输入数字(作为小数点和 . 作为千位分隔符),当他从输入框中跳出时,我们应该能够将输入文本转换为 JavaScript个数,
现在,当我们使用 Number() 函数时,它会为我们提供 Number("12,23")
的 NaN
我们可以使用新的 Intl.NumberFormat()
将英文文本转换为德文格式数字,但反之亦然。
你可以使用 numeral.js 语言环境 http://numeraljs.com/#locales
// load a locale
numeral.register('locale', 'de', {
delimiters: {
thousands: '.',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal : function (number) {
return number === 1 ? 'er' : 'ème'; //this is taken from french example, don't know in german
},
currency: {
symbol: '€' //same as above
}
});
// switch between locales
numeral.locale('de');
console.log(numeral('123,45').value());
console.log(numeral('6.123,45').value());
console.log(numeral('123,45m').value());
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
我们正在开发应同时支持德语和英语用户的应用程序。
我们可以做些什么来让德国用户以德语格式输入数字(作为小数点和 . 作为千位分隔符),当他从输入框中跳出时,我们应该能够将输入文本转换为 JavaScript个数,
现在,当我们使用 Number() 函数时,它会为我们提供 Number("12,23")
我们可以使用新的 Intl.NumberFormat()
将英文文本转换为德文格式数字,但反之亦然。
你可以使用 numeral.js 语言环境 http://numeraljs.com/#locales
// load a locale
numeral.register('locale', 'de', {
delimiters: {
thousands: '.',
decimal: ','
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal : function (number) {
return number === 1 ? 'er' : 'ème'; //this is taken from french example, don't know in german
},
currency: {
symbol: '€' //same as above
}
});
// switch between locales
numeral.locale('de');
console.log(numeral('123,45').value());
console.log(numeral('6.123,45').value());
console.log(numeral('123,45m').value());
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>