RyKilleen / rykilleen.github.io

https://www.ryankilleen.com
MIT License
0 stars 1 forks source link

Internationalization: toLocaleString(), Intl.NumberFormat etc #4

Open RyKilleen opened 6 years ago

RyKilleen commented 6 years ago

Important to keep global users in mind! Decimal points mean different things for different users.

RyKilleen commented 6 years ago

Script written for a Reddit user, for reference

function getLocalDelimiter() {
    var n = 1000;
    n = n.toLocaleString().substring(1, 2);
    return n;
  }

  var lookupDictionary = {
    3: 'Million',
    4: 'Billion',
    5: 'Trillion'
  }

  function getDelimitedArrayFromNumber(num) {
    return  num.toLocaleString().split(getLocalDelimiter());
  }
  function turnNumberIntoWords(num) {
    // Turn number into readable string, ie '1,200,000, and split it into an array 
    let numArray = getDelimitedArrayFromNumber(num); // ie ['1', '200', '000']
    let numLength = numArray.length; // 3

    if (numLength > 2) {
      let firstNumString = `${numArray[0]}.${numArray[1]}`; // '1.200'
      let firstDigits = Number(firstNumString); // 1.2

      return `${firstDigits} ${lookupDictionary[numLength]}`; // 1.2 Million
      // Same as:
      // return firstDigits + ' ' + lookupDictionary[numLength];
    } else {
      return new Intl.NumberFormat(navigator.language).format(num);
    }
  }

  turnNumberIntoWords(1000);       // '1,000'
  turnNumberIntoWords(10000);     // '10,000'
  turnNumberIntoWords(100000);   // '100,000'
  turnNumberIntoWords(1000000); // '1 Million'