1

I need to format my amounts after millions with apostrophes, after thousands with commas and decimals with periods. Using javascript. What's the best way? Thanks

Some examples:

987654321 -> 987'654,321.00
 87654321 ->  87'654,321.00
  7654321 ->   7'654,321.00
   654321 ->     654,321.00
    54321 ->      54,321.00
     4321 ->       4,321.00
      321 ->         321.00
       21 ->          21.00
        1 ->           1.00
Jacob Nuno
  • 35
  • 3

1 Answers1

1

I guess, this function can help:

function formatNumber( num ) {
  // String with formatted number
  var totalStr = '';
  // Convert number to string
  var numStr = num + '';
  // Separate number on before point and after
  var parts = numStr.split( '.' );
  // Save length of rounded number
  var numLen = parts[0].length;
  // Start iterating numStr chars
  for ( var i = 0; i < numLen; i++ ) {
    // Position of digit from end of string
    var y = numLen - i;

    // If y is divided without remainder on 3...
    if ( i > 0 && y % 3 == 0 ) {
        // add aposrtoph when greater than 6 digit
        // or add point when smaller than 6 digit
        totalStr += y >= 6 ? '\'' : ',';
    }

    // Append current position digit to total string
    totalStr += parts[0].charAt(i);
  }
  // Return total formatted string with float part of number (or '.00' when haven't float part)
  return totalStr + '.' + ( parts[1] ? parts[1] : '00');
}
StoneCountry
  • 151
  • 6