Javascript: Thousand separator

We may use following javascript function to show numbers formatted with thousands separator.


function formatThousandPlace(orgNum) {
    arr = orgNum.split('.');    //split integer part & fractional part
    intPart = arr[0];           //store integer part in a variable
    fractionPart = arr.length > 1 ? '.' + arr[1] : '';  //store fractional part in a variable
    var rgx = /(\d+)(\d{3})/;   //regexp to find thousand place
    while (rgx.test(intPart)) { 
        intPart = intPart.replace(rgx, '$1' + ',' + '$2');  //replace integer part after inserting a comma in the thousandth place
    document.write(intPart + fractionPart); //write final value to the document

Function Call
Now, we can use it anywhere in the document where we want to show those numbers. For example: it may inside normal html elements or some dynamic ASP.Net controls like GridView, DataList, FormView etc.

<script language="javascript">formatThousandPlace('10000000.00')</script>

While calling this from ItemTemplate of an ASP GridView the syntax will be

<asp:TemplateField HeaderText="Price">
       <script language="javascript">formatThousandPlace('<%#Eval("SalePrice") %>')</script>

I hope this is helpful.

Leave a Reply

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

You are commenting using your 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