WEBDOOD.COM

Arrays

Javascript Number ensureDecimalPlaces

by webdood on Nov.17, 2011, under Arrays, Javascript, Numbers

Needed a function ensure that a certain number of digits appeared after a decimal point today.

For instance 1.3 should be 1.300, 1 should be 1.000 etc.

Number.prototype.ensureDecimalPlaces = function( decimals ) {
  var tempString = this.toString(),
      pileOfPads = "000000000000000000000000",
      decimalLocation = tempString.indexOf('.');
  if (decimalLocation === -1) {
    retVal = tempString + '.' + pileOfPads.substring(0,decimals);
  } else {
    retVal = tempString + pileOfPads;
    retVal = retVal.substring(0,decimalLocation+decimals+1);
  }
  return retVal;
}

Example use:

var x = 12.3
console.log(x.ensureDecimalPlaces(3)) returns 12.300

Leave a Comment more...

Javascript Array Sort By String Length

by webdood on Jul.08, 2011, under Arrays, Javascript

Had a need to sort an array of strings by length of each string in descending order.
Simple solution, really. Perhaps may come in handy at a later date.

  ////////////////////////////////////////////////////////////////////////////
  //
  // Array.sortByStringLength() - sorts an array of strings based on length
  // ==========================
  //
  ////////////////////////////////////////////////////////////////////////////
  Array.prototype.sortByStringLength = function() {
    return this.sort( byStringLength )
  }
  function byStringLength(a,b) {//Sort function used by Array.sortByStringLength
    var retVal = 0;
    if (a.length > b.length) { retVal = -1; }
    return retVal;
  }

Shannon Norrell

2 Comments more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org