javascriptreactjsreact-intl

How to allow german user to enter numbers in german format in React JavaScript


We are developing application which should support both German and English users.

What can we do to allow German users to enter numbers in German format (, as decimal point and . as thousand separator), and moment he tab out from input box, we should be able to convert input text into JavaScript number, Right now when we use Number() function it gives us the NaN for Number("12,23")

We are able to convert English text to German format number using new Intl.NumberFormat() but it is vice versa which we want.


Solution

  • you could use numeral.js locales 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>