3

In my app, I want to format various numbers using a library, and I have a couple of related questions (which I don't submit separately because I think they might represent a very common set of problems)

  1. Format a number using a format string constant to achieve compressed literals such as 1.2k or 1.23M
  2. Format a number using a format string constant to have a thousand delimiter applied, ragardless of client's locale settings.

I tried to achieve a formatting result, where the language thousand delimiter is actually taken into consideration

http://jsfiddle.net/erbronni/19mLmekt/

// load a language
numeral.language('fr', {
    delimiters: {
        thousands: ' ',
        decimal: ','
    },
    abbreviations: {
        thousand: 'k',
        million: 'M',
        billion: '',
        trillion: 't'
    },
    ordinal : function (number) {
        return number === 1 ? 'er' : 'ème';
    },
    currency: {
        symbol: '€'
    }
});
numeral.language('fr');
document.getElementById('f1').innerHTML = numeral(12345678).format('0 000') // intended output: '12 345 678' -- does not seem to work
user776686
  • 7,933
  • 14
  • 71
  • 124

1 Answers1

6

Numeral.js has this built in. It can be easily achieved using a such as .format('0.00a').

Some full examples:

numeral(1000000).format('0a') will return 1m

numeral(250500).format('0.0a') will return 250.5k

numeral(10500).format('0.00a') will return 10.50k

Ycon
  • 1,830
  • 3
  • 27
  • 56
  • can you help me with numeral(719520111111111).format('0.00a'); it says Undefined – N.K Jun 26 '18 at 14:16
  • Are you sure you have numeral installed? Does it work for other numbers? – Ycon Jun 28 '18 at 00:24
  • Yes it is working perfectly for other stuff. For reference, have just edited the above mentioned fiddle , and have added the code in the last two lines. http://jsfiddle.net/nakulkudra/ueytroL7/ – N.K Jun 28 '18 at 07:27
  • @N.K as I can see numeral can't handle too much large numbers. Even if is defined, with trillions there are some problems too – Rajven Sep 25 '18 at 17:51