Javascript: Thousand separator


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

Definition

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">
    <ItemTemplate>
       <script language="javascript">formatThousandPlace('<%#Eval("SalePrice") %>')</script>
    </ItemTemplate>
</asp:TemplateField>

I hope this is helpful.

Advertisements