Developing Feather-Weight Webservices with JavaScript

Extending the native Number() class

The class is limited now. It should grow over time to include many more interesting methods. You can see parts of this in use in Using JS code libraries, part 2.

  Code from "Developing Featherweight Web Services with JavaScript"
  (c)An Elektrum Press, retain this notice

// decide whether commify() should really periodify() thousandths
var tmpNum = new Number(0.1);
// thousandth marker is opposite of decimal marker
Number.localeThousandth = tmpNum.toLocaleString().match(/,/) ? '.' : ',';

Number.prototype.commify = function () {
  var numStr = this.toString();
  var num = numStr.split('');

  // simplify by only accepting integers longer than 3 digits
  if ( numStr.match(/\D/) || num.length < 3 ) return numStr;
  numStr = num.join('');

  numStr = numStr.replace(/(\d\d\d)/g, "$1_marker_");
  // if we did one too many, take it back
  numStr = numStr.replace(/_marker_$/g, '');
  // replace the thousandth _marker_ with ',' or '.'
  numStr = numStr.replace(/_marker_/g, Number.localeThousandth);

  num = numStr.split('');
  return num.join('');

Live tests

« Extending the native Array() class · Code for the Args() classes »
Web Developing Featherweight Web Services with JavaScript
This is version 0.57b of this manual. It is a beta version with some gaps. We are grateful for feedback.

The code is the manual has not yet been fully tested against Internet Explorer. Bug reports are welcome.
An Elektrum Press Online