Sunday, April 16, 2017

Format currency without jQuery plugin

In this tutorial you will learn how to format currency without using any jQuery plugin.
Let’s have a look how to accomplish this

Javascript Function:-
function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}

Call of the function will be like this:
formatCurrency(8000000000);
formatCurrency(0.700);
formatCurrency(100);

Output will be
$8,000,000,000.00
$0.70
$100.00

No comments:

Post a Comment