a developer's notes – a semi-technical web development BLOG

May 7, 2013

Javascript function to convert number to currency.

Filed under: Javascript / JQuery — Duy Nguyen @ 4:25 pm
Tags: , , ,

Read Here


function format1(n, currency) {
    return currency + " " + n.toFixed(2).replace(/./g, function(c, i, a) {
        return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
    });
}

function format2(n, currency) {
    return currency + " " + n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
}

var numbers = [1, 12, 123, 1234, 12345, 123456, 1234567, 12345.67];

document.write("<p>Format #1:</p>");
for (var i = 0; i < numbers.length; i++) {
    document.write(format1(numbers[i], "£") + "<br />");
}

document.write("<p>Format #2:</p>");
for (var i = 0; i < numbers.length; i++) {
    document.write(format2(numbers[i], "$") + "<br />");
}

Here is the output

Format #1:
£ 1.00
£ 12.00
£ 123.00
£ 1,234.00
£ 12,345.00
£ 123,456.00
£ 1,234,567.00
£ 12,345.67

Format #2:
$ 1.00
$ 12.00
$ 123.00
$ 1,234.00
$ 12,345.00
$ 123,456.00
$ 1,234,567.00
$ 12,345.67
Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: