Search code examples
numeral.js

convert locale format back to default with numeral.js


I'm storing the number and currency formats in the default numeral js format. I allow the user to have their own formatting based on their locale setting. I'm trying to figure out how I can convert their custom formatting back to the default formatting in order to store it consistently and in case they change locale.

for example the current is set:

numeral.register('locale', 'fr', {
delimiters: {
    thousands: '.',
    decimal: ','
},
abbreviations: {
    thousand: 'k',
    million: 'm',
    billion: 'b',
    trillion: 't'
},
ordinal : function (number) {
    return number === 1 ? 'er' : 'ème';
},
currency: {
    symbol: '€'
}
});

When I get '0.0,00€' back as preferred formatting, how can I convert is back to the default numeral.js setting being '0,0.00$' for storage.


Solution

  • You can simply switch between locals by setting the local with numeral.local('en'). You could use a litte helper function to do that for you. You would just have to pass it the desired local and maybe your current numeral you need to be switched.

    Here is an example doing exactly that. I have also added money.js to convert between currencies. I'm sure you will get the idea.

    var yourNumeral = numeral(1234.56);
    
    // helper fn to switch local and convert.
    function switchLocal(local, num, convert) {
      numeral.locale(local);
      num.set(fx.convert(num.value(), convert)); 
      return num.format();
    }
    
    // set money.js base and rates
    fx.base = "EUR";
    fx.rates = {
      "USD" : 1.0873 // eg. 1 EUR === 1.0873 USD
    };
    
    // set default format.
    numeral.defaultFormat('0,0[.]00 $');
    // load a locale.
    numeral.register('locale', 'fr', {
      delimiters: {
        thousands: ' ',
        decimal: ','
      },
      abbreviations: {
        thousand: 'k',
        million: 'm',
        billion: 'b',
        trillion: 't'
      },
      ordinal : function (number) {
        return number === 1 ? 'er' : 'ème';
      },
      currency: {
        symbol: '€'
      }
    });
    // set the loaded local.
    numeral.locale('fr');
    
    // yourNumeral with loaded local "fr".
    console.log(yourNumeral.format());
    // yourNumeral switched local to "en" and converted from € to $.
    console.log(switchLocal('en', yourNumeral, { from: "EUR", to: "USD" }));
    // yourNumeral switched back to "fr" local and converted back to € from $.
    console.log(switchLocal('fr', yourNumeral, { from: "USD", to: "EUR" }));
    <script src="https://openexchangerates.github.io/money.js/money.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>