Showing posts with label Formatting. Show all posts
Showing posts with label Formatting. Show all posts

Number Formatting in JavaScript using toLocaleString - Thousand Separator, Currency Formatter

Number Formatting in JavaScript using toLocaleString() - Thousand Separator, Currency Formatter

Today I came across toLocaleString() in javascript which can be used for formatting numbers. Thousand separator, currency formatting etc. can be achieved using this.

var num1= 2000;
num1.toLocaleString();  // "2,000"

 Thousand separator is different for different countries. This is also possible using toLocaleString().

num1.toLocaleString("en-US");
"2,000"
num1.toLocaleString("de-DE");
"2.000"
num1.toLocaleString("ar-EG");
"٢٬٠٠٠"

Currency formatting can also be done.

num1.toLocaleString('ja-JP', { style: 'currency', currency: 'INR' })

"Rs.2,000"

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Javascript Format Date, Number and Currency - Moment.js, Numeral.js and Accounting.js

Format Date, Number and Currency - Moment.js, Numeral.js and Accounting.js

I came to know libraries which help us in formatting numbers, dates and currency.

1. Moment.js - To parse, validate, and format dates.

Examples:
moment().format('MMMM Do YYYY, h:mm:ss a'); // April 4th 2015, 3:11:47 pm
moment().format('dddd');                    // Saturday
moment().format("MMM Do YY");               // Apr 4th 15

// selecting time zone
moment.tz("2015-04-04 11:55", "Indian/Mauritius").format(); // "2015-04-04T11:55:00+04:00"
moment.tz("March 12th 2015 8PM", "MMM Do YYYY hA", "Indian/Mauritius").format();
 // "2015-03-12T20:00:00+04:00"


Url: http://momentjs.com/


2. Numeral.js - To format numbers

Examples:
numeral(10000).format('0,0'); // "10,000"
numeral(10000).format('$0,0');  // "$10,000"
numeral(10000).format('0b'); // "10KB"
numeral(0.10).format('0%'); // "10%"

Url: http://numeraljs.com/

3. Accounting.js - To format numbers, money and currency

Examples:
accounting.formatMoney(1000); // "$1,000.00"

// Indian rupee currency formatting
accounting.formatMoney(1000.99, "₹", 2, ".", ","); // "₹1.000,99"

Url: http://openexchangerates.github.io/accounting.js/