Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    Senior Coder
    Join Date
    Jul 2003
    Location
    My pimped-out igloo in Canadia
    Posts
    1,966
    Thanks
    36
    Thanked 0 Times in 0 Posts

    format variable output to use 'thousands' indicator (put a comma every 3 numbers)

    Hey,

    Quick and simple

    I need to be able to format numbers to display as '1,000 or 1,234,457' etc instead of 1000 or 1234457 using JS.

    what would be the simplest way to do it? Perhaps it would be best if I gave whatever container they were in a class name and the script would apply it accordingly.
    Before you criticize someone, you should walk a mile in their shoes. That way, when you criticize them, you're a mile away and you have their shoes :)

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,037
    Thanks
    203
    Thanked 2,539 Times in 2,517 Posts
    Here you are:-

    <script type = "text/javascript">

    var num = 1234567890123;
    document.write('<span id="count"></span>');
    document.getElementById('count').innerHTML = addCommas(String(num));

    function addCommas(nStr) {
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1' + ',' + '$2');
    }
    return nStr;
    }

    </script>

  • #3
    Senior Coder
    Join Date
    Jul 2003
    Location
    My pimped-out igloo in Canadia
    Posts
    1,966
    Thanks
    36
    Thanked 0 Times in 0 Posts
    Hey Phillip

    I'm sorry, i should have been more specific

    Variables will be coming out of a database into an HTML table. Certain columns will contain numbers, which have to be formatted in 'thousands'. I assume that if I set certain columns with a class, the script could convert the numbers into thousands (if they are over 1000)
    Before you criticize someone, you should walk a mile in their shoes. That way, when you criticize them, you're a mile away and you have their shoes :)

  • #4
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,037
    Thanks
    203
    Thanked 2,539 Times in 2,517 Posts

  • #5
    Regular Coder 2reikis's Avatar
    Join Date
    Nov 2005
    Location
    California
    Posts
    167
    Thanks
    17
    Thanked 13 Times in 13 Posts

    How are you getting info from DB?

    If you're using PHP to get your info and you don't need the number as number, you can use the PHP function number_format.

    PHP Code:
    <?php
    $theNumber 
    1024.17304//number_format needs Float as first arg
    $theNumberFormatted number_format($theNumber,2);
    echo 
    $theNumberFormatted;
    // outputs 1,024.17
    ?>
    HTH

    2reikis
    Last edited by 2reikis; 08-28-2007 at 08:17 PM. Reason: clarification

  • Users who have thanked 2reikis for this post:

    Philip M (08-28-2007)

  • #6
    Senior Coder
    Join Date
    Jul 2003
    Location
    My pimped-out igloo in Canadia
    Posts
    1,966
    Thanks
    36
    Thanked 0 Times in 0 Posts
    I apologize, I'm a trying to help a friend so i'm a little hazy on the details

    I had a look at the link Phil, and it helped me refine my technique however that deals with modifying tables by row, not column.

    could we do something like

    Code:
    <script>
    function getElementsByClassName(classname) {
        if (document.getElementsByTagName) {
             var els = document.getElementsByTagName("*");
             var c = new RegExp('/b^|' + classname + '|$/b');
             final = new Array();
             var n=0;
             for (var i=0; i < els.length; i++) {
                  if (els[i].className) {
                       if(c.test(els[i].className)) {
                       final[n] = els[i];
                       n++;
                       }
                  }
             }
             return final;
        } else{return false;}
    }
    
    document.getElementByClass('thousands').innerHTML = addCommas(String(num));
    
    function addCommas(nStr) {
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1' + ',' + '$2');
    }
    return nStr;
    }
    </script>
    or even better yet, could we write a script that uses a loop to apply the script directly to all cells in a certain column or columns, and have an onload call like 'onload="formatThousands('tableID','col3','col4','col5')?

    That would avoid the need to give them classes altogether
    Before you criticize someone, you should walk a mile in their shoes. That way, when you criticize them, you're a mile away and you have their shoes :)

  • #7
    Senior Coder
    Join Date
    Jul 2003
    Location
    My pimped-out igloo in Canadia
    Posts
    1,966
    Thanks
    36
    Thanked 0 Times in 0 Posts
    I found out that he is using VB to render the table... could the formatting be done as he creates the table?

    Code:
    'Create HTML header for each email address
                    sr = New StreamWriter(filepath & "\customer report.html", False)
                    sr.Write("<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN""><html><head><title>Untitled Document</title> " & _
                            "<meta http-equiv=""Content-Type"" content=""text/html; charset=iso-8859-1""> " & _
                            "<style type=""text/css"">* { padding: 0px; margin: 0px }" & _
                            "body { background-color: white; font-size: 12px } " & _
                            "table { border-collapse: collapse; width: auto; font-size: 11px } " & _
                            "td { border: 1px solid black; } " & _
                            ".columnHeaders { text-align: center; } " & _
                            ".columnHeaders td { padding: 5px } " & _
                            ".info td { padding: 2px } " & _
                            "</style></head><body><br> " & _
                            "<table id=""mainTable""  cellspacing=""0"" cellpadding=""0""> " & _
                            "<tr class=""columnHeaders""> " & _
                            "<td>Customer Number</td><td>Customer Name</td><td>Address 1</td><td>Address 2</td><td>City</td><td>State</td> " & _
                            "<td>Postal-Zip Code</td><td>Terms</td><td>Credit Limit</td><td>Prev. Credit Limit</td><td>Credit Entry Date</td><td>Customer Since</td></tr>")
    
    
                    'Get all salesman codes for each unique email address
                    SQL = "select salesman_cd from salesman where representative_email = '" & strCurrentEmail & "'"
                    objDAdapter.SelectCommand = New SqlClient.SqlCommand(SQL, sqlConMts)
    
                    objDAdapter.Fill(objDataSet)
                    strXmlHeaderCode = objDataSet.GetXml
                    objDataSet.Clear()
                    Dim intCodeCTR As Integer = objXMLfn.fnGetCount(strXmlHeaderCode) - 1
    
                    If intCodeCTR >= 0 Then
                        strAllSalesman = "cd.salesman_cd in ('" & objXMLfn.fnGetValue("/NewDataSet/Table[0]/salesman_cd", strXmlHeaderCode) & "'"
    
    
                        For intLoopCTR2 = 1 To intCodeCTR
    
                            strAllSalesman = strAllSalesman + ", '" & objXMLfn.fnGetValue("/NewDataSet/Table[" & intLoopCTR2 & "]/salesman_cd", strXmlHeaderCode) & "'"
    
                        Next
    
                        strAllSalesman = strAllSalesman + ")"
    
                        'Get new customers or customers with new terms for every salesman code
                        SQL = "select cd.salesman_cd, c.customer_no, c.customer_name, c.customer_address1, c.customer_address2, c.customer_city, c.customer_state, c.customer_postal_cd, cd.terms_cd, t.terms_desc, convert(integer,c.credit_limit) as credit_limit, convert(varchar, c.credit_limit_entry_dte, 101) as credit_limit_entry_dte, convert(varchar, c.customer_since, 101) as customer_since, c.previous_cl " & _
                                "from customer c " & _
                                "left join customer_division cd on cd.customer_no = c.customer_no and cd.division_no = '01' " & _
                                "left join terms t on t.terms_cd = cd.terms_cd " & _
                                "where ((credit_limit_entry_dte >= '" & strStartDate & "' and credit_limit_entry_dte <= '" & strEndDate & "') or (customer_since >= '" & strStartDate & "' and customer_since <= '" & strEndDate & "')) and " & strAllSalesman
    
                        objDAdapter.SelectCommand = New SqlClient.SqlCommand(SQL, sqlConMts)
    
                        objDAdapter.Fill(objDataSet)
                        strXmlHeaderCustomer = objDataSet.GetXml
                        objDataSet.Clear()
                        Dim intCustCTR As Integer = objXMLfn.fnGetCount(strXmlHeaderCustomer) - 1
    
                        If intCustCTR >= 0 Then
    
                            For intLoopCTR3 = 0 To intCustCTR
    
                                'Write table row for each detail line
    
                                sr.Write("<tr class=""info"">")
                                'sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/salesman_cd", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/customer_no", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/customer_name", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/customer_address1", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/customer_address2", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/customer_city", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/customer_state", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/customer_postal_cd", strXmlHeaderCustomer) & "</td>")
                                'sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/terms_cd", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/terms_desc", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/credit_limit", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/previous_cl", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/credit_limit_entry_dte", strXmlHeaderCustomer) & "</td>")
                                sr.Write("<td>" & fnGetValue("/NewDataSet/Table[" & intLoopCTR3 & "]/customer_since", strXmlHeaderCustomer) & "</td>")
                                sr.Write("</tr>")
    
                            Next
    
                            'End HTML file
                            sr.Write("</table></body></html>")
                            sr.Close()
    Before you criticize someone, you should walk a mile in their shoes. That way, when you criticize them, you're a mile away and you have their shoes :)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •