4/20/14

Format Currency with JavaScript and CSS

When working with currency, there is a need to format the data with commas, decimals, currency sign and an indicator for negative amounts. Let’s take a look at one approach that can help us format the data once it is rendered on the user interface.

We start by taking a look at a page that displays several numeric fields with no styles.



As we can see, these numbers are hard to read. It will be much better to just add commas and a different font for negative values. We can do this by using a CSS selector and select all the elements that we want to format.

$('* div').each(function () {   
    var item = $(this).text();
    var num = Number(item).toLocaleString('en');

    if (Number(item) < 0) {
        num = num.replace('-', '');
        $(this).addClass('negMoney');
    } else {
        $(this).addClass('enMoney');
    }

    $(this).text(num);
});

The approach here is to use the Number.toLocaleString function to format the data with commas. This provides the ability to eliminate the use of regular expression to parse the data. Now we need to add the currency sign and use a red font for negative amounts. We do this by applying these CSS classes.

.enMoney::before {
    content:"$";
}
.negMoney {
    color:red;
}
div.negMoney::before {
    content:'($';
}
div.negMoney::after {
    content:')';
}

The script adds the class name to the element. We use the enMoney and negMoney classes to provide the font style. To add the currency sign and parentheses (negative values only), we use the CSS pseudo-element ::before and ::after to apply the special currency format.  The result looks like this:




This looks much better now, and it is a simple approach that uses the browser capabilities, JavaScript and some CSS to get the formatting done.

Use this JSFiddle to play with the script: Format Currency


0 comments :

Post a Comment

What do you think?