Log In
New Account
  
Home My Page Project Cloud Code Snippets Project Openings

Browse | Submit A New Snippet | Create A Package

 

num2money

Type:
Function
Category:
Math Functions
License:
GNU General Public License
Language:
JavaScript
 
Description:
Format numbers as money in JavaScript

Versions Of This Snippet::

Victor Marcov
Snippet ID Download Version Date Posted Author Delete
191.12012-04-28 22:23Victor Marcov
Changes since last version::
some fixes
181.02012-04-28 22:20Victor Marcov

Download a raw-text version of this code by clicking on "Download Version"

 


Latest Snippet Version: :1.1

Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)
{ 
   var n = this,
   c = isNaN(decimals) ? 2 : Math.abs(decimals), //if decimal is zero we must take it, it means user does not want to show any decimal
   d = decimal_sep || ',', //if no decimal separetor is passed we use the comma as default decimal separator (we MUST use a decimal separator)

   /*
   according to [http://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
   the fastest way to check for not defined parameter is to use typeof value === 'undefined' 
   rather than doing value === undefined.
   */   
   t = (typeof thousands_sep === 'undefined') ? '.' : thousands_sep, //if you don't want ot use a thousands separator you can pass empty string as thousands_sep value

   sign = (n < 0) ? '-' : '',

   //extracting the absolute value of the integer part of the number and converting to string
   i = parseInt(n = Math.abs(n).toFixed(c)) + '', 

   j = ((j = i.length) > 3) ? j % 3 : 0; 
   return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); 
}
		

Submit a new version

You can submit a new version of this snippet if you have modified it and you feel it is appropriate to share with others..


Terms of Use    Privacy Policy    Contribution Guidelines    Feedback

Powered By GForge Collaborative Development Environment