Formatting the results of a calculation

Discussion in 'Javascript' started by KsAdmin, Jul 6, 2004.

  1. KsAdmin

    KsAdmin Guest

    I have a question which has had me stumped for a few days now. I have
    a form that I add the values of fields together and display the total
    in a total field. I have the calculations working correctly. My
    problem is that I would like to change the format of the total from
    1234567 to 1,234,567 . Is this possible using javascript? Here is the
    code that I use to do the calculations. I have edited out all the code
    that I use to validate the fields because I don't think it is needed
    for this question.

    Thanks in advance.

    function calculateTotal(){
    var
    fields=Array("life1","life2","life3","life4","life5","life6");
    for(i=0;i<fields.length;i++){
    str="var
    val"+i+"=parseInt(document.frmLifeNeed."+fields+".value);";
    eval(str);
    }
    total=val0+val1+val2+val3+val4-val5
    document.frmLifeNeed.total.value = total;
    }
    Josh Austin
    System Administrator
    Agent Services of America
    ksadmin NOSPAM @comcast.net
    (remove NOSPAM and the spaces out of my email address to send email)
    KsAdmin, Jul 6, 2004
    #1
    1. Advertising

  2. KsAdmin

    Ivo Guest

    "KsAdmin" wrote
    > in a total field. I have the calculations working correctly. My
    > problem is that I would like to change the format of the total from
    > 1234567 to 1,234,567 . Is this possible using javascript? Here is the


    See this:
    <script>
    var n=1234567;
    n=''+n;
    var s='';
    var l=n.length;
    while(l>0){
    s=','+n.substring(l-3,l)+s;
    l-=3;
    }
    s=s.substring(1);
    alert(s);
    </script>
    HTH
    Ivo
    Ivo, Jul 6, 2004
    #2
    1. Advertising

  3. KsAdmin

    KsAdmin Guest

    Can't seem to get this to work,
    when it runs it pops an alert box with 1234567 in it instead of the
    value of the calculation with the commas in place.
    On Tue, 6 Jul 2004 19:46:24 +0200, "Ivo" <> wrote:

    >"KsAdmin" wrote
    >> in a total field. I have the calculations working correctly. My
    >> problem is that I would like to change the format of the total from
    >> 1234567 to 1,234,567 . Is this possible using javascript? Here is the

    >
    >See this:
    ><script>
    >var n=1234567;
    >n=''+n;
    >var s='';
    >var l=n.length;
    >while(l>0){
    > s=','+n.substring(l-3,l)+s;
    > l-=3;
    >}
    >s=s.substring(1);
    >alert(s);
    ></script>
    >HTH
    >Ivo
    >


    Josh Austin
    System Administrator
    Agent Services of America
    ksadmin NOSPAM @comcast.net
    (remove NOSPAM and the spaces out of my email address to send email)
    KsAdmin, Jul 6, 2004
    #3
  4. KsAdmin

    Mick White Guest

    KsAdmin wrote:

    <snip>

    I would like to change the format of the total from
    > 1234567 to 1,234,567 . Is this possible using javascript? Here is the
    > code that I use to do the calculations. I have edited out all the code
    > that I use to validate the fields because I don't think it is needed
    > for this question.


    // Use getDecimal() function to get the decimal portion of a number.
    // Use this func if you are sure "val" evaluates to a number.
    // More reliable than: return val-Math.floor(val), which should
    // return the decimal portion, but doesn't always.

    function getDecimal(val){
    val+="";
    return val.substring(val.indexOf("."));
    }

    // Use commaThis() function to convert a numerical expression
    // to a number with commas(a String), e.g. 10000.25 to "10,000.25"
    // Use this func if you are sure "entry" evaluates to a number.

    function commaThis(entry) {
    entry=Math.floor(entry)+""
    var rex = /(-?\d+)(\d{3})/
    while (rex.test(entry)) {
    entry = entry.replace(rex, "$1,$2")
    }
    return entry+getDecimal(entry);
    }


    Mick
    Mick White, Jul 6, 2004
    #4
  5. KsAdmin

    KsAdmin Guest

    sorry, I don't mean to sound dumb.... just got back from holiday so I
    am not coding up to par lol.
    how do I get the commaThis() function to convert the numerical
    expression in the total form field?

    total=val0+val1+val2+val3+val4-val5
    document.frmLifeNeed.total.value = total;

    On Tue, 06 Jul 2004 18:22:12 GMT, Mick White
    <> wrote:

    >KsAdmin wrote:
    >
    ><snip>
    >
    > I would like to change the format of the total from
    >> 1234567 to 1,234,567 . Is this possible using javascript? Here is the
    >> code that I use to do the calculations. I have edited out all the code
    >> that I use to validate the fields because I don't think it is needed
    >> for this question.

    >
    >// Use getDecimal() function to get the decimal portion of a number.
    >// Use this func if you are sure "val" evaluates to a number.
    >// More reliable than: return val-Math.floor(val), which should
    >// return the decimal portion, but doesn't always.
    >
    >function getDecimal(val){
    >val+="";
    >return val.substring(val.indexOf("."));
    >}
    >
    >// Use commaThis() function to convert a numerical expression
    >// to a number with commas(a String), e.g. 10000.25 to "10,000.25"
    >// Use this func if you are sure "entry" evaluates to a number.
    >
    >function commaThis(entry) {
    >entry=Math.floor(entry)+""
    >var rex = /(-?\d+)(\d{3})/
    >while (rex.test(entry)) {
    >entry = entry.replace(rex, "$1,$2")
    >}
    >return entry+getDecimal(entry);
    >}
    >
    >
    >Mick


    Josh Austin
    System Administrator
    Agent Services of America
    ksadmin NOSPAM @comcast.net
    (remove NOSPAM and the spaces out of my email address to send email)
    KsAdmin, Jul 6, 2004
    #5
  6. KsAdmin

    Alberto Guest

    Mah the following should work, it's a bit longer for it takes into account
    also possible floating decimal parts.
    I hope no typo or gross misconception is in it but it seems fine to me.
    Rebuild lines that the mail viewer may have broken.

    <script>
    var n=1234567890.5502;

    function nFormat(n){
    //validate
    if(typeof(parseFloat(n))!="number"){return false;};
    n+="";
    //initialize
    var begin=0, middle="", tail="";
    if(n.indexOf(".")>-1){
    tail=n.substring( n.indexOf(".") );//floating tail first!
    n=n.substring( 0, n.indexOf(".") );
    };
    //RUN
    for(var i=n.length-3; i>0; i-=3, begin++){
    middle=","+n.substring(i, i+3)+middle;
    }
    //return
    return n.substring(0, n.length-(middle.length-begin) )+middle+tail;
    }

    alert( nFormat(n) );
    </script>

    I hope this helps
    ciao
    Alberto
    http://www.unitedscripters.com/



    "KsAdmin" <ksadmin > ha scritto nel messaggio
    news:...
    > I have a question which has had me stumped for a few days now. I have
    > a form that I add the values of fields together and display the total
    > in a total field. I have the calculations working correctly. My
    > problem is that I would like to change the format of the total from
    > 1234567 to 1,234,567 . Is this possible using javascript? Here is the
    > code that I use to do the calculations. I have edited out all the code
    > that I use to validate the fields because I don't think it is needed
    > for this question.
    >
    > Thanks in advance.
    >
    > function calculateTotal(){
    > var
    > fields=Array("life1","life2","life3","life4","life5","life6");
    > for(i=0;i<fields.length;i++){
    > str="var
    > val"+i+"=parseInt(document.frmLifeNeed."+fields+".value);";
    > eval(str);
    > }
    > total=val0+val1+val2+val3+val4-val5
    > document.frmLifeNeed.total.value = total;
    > }
    > Josh Austin
    > System Administrator
    > Agent Services of America
    > ksadmin NOSPAM @comcast.net
    > (remove NOSPAM and the spaces out of my email address to send email)
    Alberto, Jul 6, 2004
    #6
  7. KsAdmin

    Alberto Guest

    Though I don't mean to answer on behalf of Mick, I think he certainly meant
    that you must pass to his function the sum as already calculated.
    If you prefer, arguably:
    var total = commaThis( val0+val1+val2+val3+val4-val5 );

    ciao
    Alberto
    http://www.unitedscripters.com/

    "KsAdmin" <ksadmin > ha scritto nel messaggio
    news:...
    > sorry, I don't mean to sound dumb.... just got back from holiday so I
    > am not coding up to par lol.
    > how do I get the commaThis() function to convert the numerical
    > expression in the total form field?
    >
    > total=val0+val1+val2+val3+val4-val5
    > document.frmLifeNeed.total.value = total;
    >
    > On Tue, 06 Jul 2004 18:22:12 GMT, Mick White
    > <> wrote:
    >
    > >KsAdmin wrote:
    > >
    > ><snip>
    > >
    > > I would like to change the format of the total from
    > >> 1234567 to 1,234,567 . Is this possible using javascript? Here is the
    > >> code that I use to do the calculations. I have edited out all the code
    > >> that I use to validate the fields because I don't think it is needed
    > >> for this question.

    > >
    > >// Use getDecimal() function to get the decimal portion of a number.
    > >// Use this func if you are sure "val" evaluates to a number.
    > >// More reliable than: return val-Math.floor(val), which should
    > >// return the decimal portion, but doesn't always.
    > >
    > >function getDecimal(val){
    > >val+="";
    > >return val.substring(val.indexOf("."));
    > >}
    > >
    > >// Use commaThis() function to convert a numerical expression
    > >// to a number with commas(a String), e.g. 10000.25 to "10,000.25"
    > >// Use this func if you are sure "entry" evaluates to a number.
    > >
    > >function commaThis(entry) {
    > >entry=Math.floor(entry)+""
    > >var rex = /(-?\d+)(\d{3})/
    > >while (rex.test(entry)) {
    > >entry = entry.replace(rex, "$1,$2")
    > >}
    > >return entry+getDecimal(entry);
    > >}
    > >
    > >
    > >Mick

    >
    > Josh Austin
    > System Administrator
    > Agent Services of America
    > ksadmin NOSPAM @comcast.net
    > (remove NOSPAM and the spaces out of my email address to send email)
    Alberto, Jul 6, 2004
    #7
  8. KsAdmin

    Mick White Guest

    Ivo wrote:

    > "KsAdmin" wrote
    >
    >>in a total field. I have the calculations working correctly. My
    >>problem is that I would like to change the format of the total from
    >>1234567 to 1,234,567 . Is this possible using javascript? Here is the

    >
    >
    > See this:
    > <script>
    > var n=1234567;
    > n=''+n;
    > var s='';
    > var l=n.length;
    > while(l>0){
    > s=','+n.substring(l-3,l)+s;
    > l-=3;
    > }
    > s=s.substring(1);
    > alert(s);
    > </script>
    > HTH
    > Ivo
    >

    Try: var n=-341234567.33333;
    Mick
    Mick White, Jul 6, 2004
    #8
  9. KsAdmin

    Alberto Guest

    Mick made an excellent point: negative numbers!

    Ok, my personal proposal (without meaning either better or worse of any
    other, just one of the many ways to do the same thing) and which takes into
    account <0 numbers too is then:

    <script>
    var n=-1234567890.5502;

    function nFormat(n){
    //validate
    if(typeof(parseFloat(n))!="number"){return false;};
    //initialize
    var begin=0, middle="", tail="", s=(n<0)?"-":"";
    n=Math.abs(n)+"";
    if(n.indexOf(".")>-1){
    tail=n.substring( n.indexOf(".") ); n=n.substring( 0, n.indexOf(".") );
    };
    //RUN
    for(var i=n.length-3; i>0; i-=3, begin++)middle=","+n.substring(i,
    i+3)+middle;
    //return
    return s+n.substring(0, n.length-(middle.length-begin) )+middle+tail;
    }

    alert( nFormat(n) );
    </script>

    I hope it is of some help
    ciao
    http://www.unitedscripters.com/
    Alberto, Jul 6, 2004
    #9
  10. KsAdmin

    Alberto Guest

    Slightly better, I added a parseFloat

    <script>
    var n=-1234567890.5502;

    function nFormat(n){
    //validate
    if(typeof(parseFloat(n))!="number"){return false;};
    //initialize
    var begin=0, middle="", tail="", s=(parseFloat(n)<0)?"-":"";
    n=Math.abs(n)+"";
    if(n.indexOf(".")>-1){
    tail=n.substring( n.indexOf(".") );//floating tail first!
    n=n.substring( 0, n.indexOf(".") );
    };
    //RUN
    for(var i=n.length-3; i>0; i-=3, begin++)middle=","+n.substring(i,
    i+3)+middle;
    //return
    return s+n.substring(0, n.length-(middle.length-begin) )+middle+tail;
    }

    alert( nFormat(n) );
    </script>

    well, time to go have dinner on this side of the pond!
    ciao
    Alberto
    http://www.unitedscripters.com/
    Alberto, Jul 6, 2004
    #10
  11. KsAdmin

    KsAdmin Guest

    I'm sorry for being so slow today.....
    how do I call this function from my function that I use to complete
    the calculations (see original post) and how do I get the reformatted
    string to display in the form field Text?
    On Tue, 06 Jul 2004 19:14:35 GMT, "Alberto" <>
    wrote:

    >Mick made an excellent point: negative numbers!
    >
    >Ok, my personal proposal (without meaning either better or worse of any
    >other, just one of the many ways to do the same thing) and which takes into
    >account <0 numbers too is then:
    >
    ><script>
    >var n=-1234567890.5502;
    >
    >function nFormat(n){
    >//validate
    >if(typeof(parseFloat(n))!="number"){return false;};
    >//initialize
    >var begin=0, middle="", tail="", s=(n<0)?"-":"";
    >n=Math.abs(n)+"";
    >if(n.indexOf(".")>-1){
    >tail=n.substring( n.indexOf(".") ); n=n.substring( 0, n.indexOf(".") );
    >};
    >//RUN
    >for(var i=n.length-3; i>0; i-=3, begin++)middle=","+n.substring(i,
    >i+3)+middle;
    >//return
    >return s+n.substring(0, n.length-(middle.length-begin) )+middle+tail;
    >}
    >
    >alert( nFormat(n) );
    ></script>
    >
    >I hope it is of some help
    >ciao
    >http://www.unitedscripters.com/
    >


    Josh Austin
    System Administrator
    Agent Services of America
    ksadmin NOSPAM @comcast.net
    (remove NOSPAM and the spaces out of my email address to send email)
    KsAdmin, Jul 6, 2004
    #11
  12. KsAdmin

    Mick White Guest

    KsAdmin wrote:

    > how do I get the commaThis() function to convert the numerical
    > expression in the total form field?
    >
    > total=val0+val1+val2+val3+val4-val5
    > document.frmLifeNeed.total.value = total;


    document.frmLifeNeed.total.value= commaThis(val0+val1+val2+val3+val4-val5)

    As long as val0, val1...valn are Number objects, if they are String
    representation of numbers:
    commaThis((+val0)+(+val1)+(+val2)+(+val3)+(+val4)-val5)

    Subtraction automatically converts the strings to numbers (briefly).
    Addition will concatenate strings:
    "1"+2 evaluates to "12" (String)
    +"1"+2 evaluates to 3 (Number)
    "1"-"2" evaluates to -1 (Number)
    Mick
    Mick White, Jul 6, 2004
    #12
  13. KsAdmin

    Alberto Guest

    you can just do as Mick suggested for his version, say

    document.yourFormName.yourFieldName.value=
    nFormat(num1+num2+num3)

    please note that if you're drawing your numbers from form fields, they are
    all invariably String data type.
    If so, perform your sum first. I normally use parseFloat

    total=parseFloat(num1) + parseFloat(num2) + parseFloat(num3);

    Do not use parseInt().
    Then:

    document.yourFormName.yourFieldName.value = nFormat(total)

    "KsAdmin" <ksadmin > ha scritto nel messaggio
    news:...
    > I'm sorry for being so slow today.....
    > how do I call this function from my function that I use to complete
    > the calculations (see original post) and how do I get the reformatted
    > string to display in the form field Text?
    > On Tue, 06 Jul 2004 19:14:35 GMT, "Alberto" <>
    > wrote:
    >
    > >Mick made an excellent point: negative numbers!
    > >
    > >Ok, my personal proposal (without meaning either better or worse of any
    > >other, just one of the many ways to do the same thing) and which takes

    into
    > >account <0 numbers too is then:
    > >
    > ><script>
    > >var n=-1234567890.5502;
    > >
    > >function nFormat(n){
    > >//validate
    > >if(typeof(parseFloat(n))!="number"){return false;};
    > >//initialize
    > >var begin=0, middle="", tail="", s=(n<0)?"-":"";
    > >n=Math.abs(n)+"";
    > >if(n.indexOf(".")>-1){
    > >tail=n.substring( n.indexOf(".") ); n=n.substring( 0, n.indexOf(".") );
    > >};
    > >//RUN
    > >for(var i=n.length-3; i>0; i-=3, begin++)middle=","+n.substring(i,
    > >i+3)+middle;
    > >//return
    > >return s+n.substring(0, n.length-(middle.length-begin) )+middle+tail;
    > >}
    > >
    > >alert( nFormat(n) );
    > ></script>
    > >
    > >I hope it is of some help
    > >ciao
    > >http://www.unitedscripters.com/
    > >

    >
    > Josh Austin
    > System Administrator
    > Agent Services of America
    > ksadmin NOSPAM @comcast.net
    > (remove NOSPAM and the spaces out of my email address to send email)
    Alberto, Jul 6, 2004
    #13
  14. KsAdmin

    Alberto Guest

    Oh I see, you want the full script including your own function.
    Ok I have done it, fixing a few things in your function too (like an
    initialization by constructor Array without using the keyword new)


    <script>
    function nFormat(n){
    //validate
    if(typeof(parseFloat(n))!="number"){return false;};
    //initialize
    var begin=0, middle="", tail="", s=(parseFloat(n)<0)?"-":"";
    n=Math.abs(n)+"";
    if(n.indexOf(".")>-1){
    tail=n.substring( n.indexOf(".") );//floating tail first!
    n=n.substring( 0, n.indexOf(".") );
    };
    //RUN
    for(var i=n.length-3; i>0; i-=3, begin++)middle=","+n.substring(i,
    i+3)+middle;
    //return
    return s+n.substring(0, n.length-(middle.length-begin) )+middle+tail;
    }

    function calculateTotal(){
    var fields=new Array("life1","life2","life3","life4","life5","life6");
    var total=0;
    for(i=0;i<fields.length;i++){
    var aval=parseFloat(document.frmLifeNeed[fields].value);
    total+=(aval)?aval:0;//avoids NaN
    }
    document.frmLifeNeed.total.value = nFormat(total);
    }

    calculateTotal(); /*call this AFTER your form elements, or by an event
    handler like onClick="calculateTotal();" */
    </script>

    ciao
    Alberto
    http://www.unitedscripters.com/





    "KsAdmin" <ksadmin > ha scritto nel messaggio
    news:...
    > I'm sorry for being so slow today.....
    > how do I call this function from my function that I use to complete
    > the calculations (see original post) and how do I get the reformatted
    > string to display in the form field Text?
    Alberto, Jul 6, 2004
    #14
  15. KsAdmin

    KsAdmin Guest

    Ok, i got this working like so....


    function getDecimal(val){
    val+="";
    return val.substring(val.indexOf("."));
    }

    function commaThis(entry) {
    entry=Math.floor(entry)+""
    var rex = /(-?\d+)(\d{3})/
    while (rex.test(entry)) {
    entry = entry.replace(rex, "$1,$2")
    }
    return entry+getDecimal(entry);
    }

    //math portion

    var fields=Array("life1","life2","life3","life4","life5","life6");

    for(i=0;i<fields.length;i++){
    str="var
    val"+i+"=parseInt(document.frmLifeNeed."+fields+".value);";
    eval(str);
    }
    //watch word wrap here
    document.frmLifeNeed.total.value =
    commaThis(val0+val1+val2+val3+val4-val5);



    It displays the total with the proper commas now.... it just displays
    the total twice..... ex. 4,5004,500 Instead of 4,500

    any ideas?

    On Tue, 06 Jul 2004 18:22:12 GMT, Mick White
    <> wrote:

    >KsAdmin wrote:
    >
    ><snip>
    >
    > I would like to change the format of the total from
    >> 1234567 to 1,234,567 . Is this possible using javascript? Here is the
    >> code that I use to do the calculations. I have edited out all the code
    >> that I use to validate the fields because I don't think it is needed
    >> for this question.

    >
    >// Use getDecimal() function to get the decimal portion of a number.
    >// Use this func if you are sure "val" evaluates to a number.
    >// More reliable than: return val-Math.floor(val), which should
    >// return the decimal portion, but doesn't always.
    >
    >function getDecimal(val){
    >val+="";
    >return val.substring(val.indexOf("."));
    >}
    >
    >// Use commaThis() function to convert a numerical expression
    >// to a number with commas(a String), e.g. 10000.25 to "10,000.25"
    >// Use this func if you are sure "entry" evaluates to a number.
    >
    >function commaThis(entry) {
    >entry=Math.floor(entry)+""
    >var rex = /(-?\d+)(\d{3})/
    >while (rex.test(entry)) {
    >entry = entry.replace(rex, "$1,$2")
    >}
    >return entry+getDecimal(entry);
    >}
    >
    >
    >Mick


    Josh Austin
    System Administrator
    Agent Services of America
    ksadmin NOSPAM @comcast.net
    (remove NOSPAM and the spaces out of my email address to send email)
    KsAdmin, Jul 6, 2004
    #15
  16. KsAdmin

    KsAdmin Guest

    Ok figured it out,
    function commaThis(entry) {
    entry=Math.floor(entry)+""
    var rex = /(-?\d+)(\d{3})/
    while (rex.test(entry)) {
    entry = entry.replace(rex, "$1,$2")
    }
    return entry;
    }

    instead of
    return entry+getDecimal(entry);
    On Tue, 06 Jul 2004 15:45:39 -0400, KsAdmin <ksadmin
    > wrote:

    >Ok, i got this working like so....
    >
    >
    >function getDecimal(val){
    >val+="";
    >return val.substring(val.indexOf("."));
    >}
    >
    >function commaThis(entry) {
    >entry=Math.floor(entry)+""
    >var rex = /(-?\d+)(\d{3})/
    >while (rex.test(entry)) {
    >entry = entry.replace(rex, "$1,$2")
    >}
    >return entry+getDecimal(entry);
    >}
    >
    >//math portion
    >
    >var fields=Array("life1","life2","life3","life4","life5","life6");
    >
    > for(i=0;i<fields.length;i++){
    > str="var
    >val"+i+"=parseInt(document.frmLifeNeed."+fields+".value);";
    > eval(str);
    > }
    >//watch word wrap here
    >document.frmLifeNeed.total.value =
    >commaThis(val0+val1+val2+val3+val4-val5);
    >
    >
    >
    >It displays the total with the proper commas now.... it just displays
    >the total twice..... ex. 4,5004,500 Instead of 4,500
    >
    >any ideas?
    >
    >On Tue, 06 Jul 2004 18:22:12 GMT, Mick White
    ><> wrote:
    >
    >>KsAdmin wrote:
    >>
    >><snip>
    >>
    >> I would like to change the format of the total from
    >>> 1234567 to 1,234,567 . Is this possible using javascript? Here is the
    >>> code that I use to do the calculations. I have edited out all the code
    >>> that I use to validate the fields because I don't think it is needed
    >>> for this question.

    >>
    >>// Use getDecimal() function to get the decimal portion of a number.
    >>// Use this func if you are sure "val" evaluates to a number.
    >>// More reliable than: return val-Math.floor(val), which should
    >>// return the decimal portion, but doesn't always.
    >>
    >>function getDecimal(val){
    >>val+="";
    >>return val.substring(val.indexOf("."));
    >>}
    >>
    >>// Use commaThis() function to convert a numerical expression
    >>// to a number with commas(a String), e.g. 10000.25 to "10,000.25"
    >>// Use this func if you are sure "entry" evaluates to a number.
    >>
    >>function commaThis(entry) {
    >>entry=Math.floor(entry)+""
    >>var rex = /(-?\d+)(\d{3})/
    >>while (rex.test(entry)) {
    >>entry = entry.replace(rex, "$1,$2")
    >>}
    >>return entry+getDecimal(entry);
    >>}
    >>
    >>
    >>Mick

    >
    >Josh Austin
    >System Administrator
    >Agent Services of America
    >ksadmin NOSPAM @comcast.net
    >(remove NOSPAM and the spaces out of my email address to send email)


    Josh Austin
    System Administrator
    Agent Services of America
    ksadmin NOSPAM @comcast.net
    (remove NOSPAM and the spaces out of my email address to send email)
    KsAdmin, Jul 6, 2004
    #16
  17. KsAdmin

    Mick White Guest

    Alberto wrote:

    > Mah the following should work, it's a bit longer for it takes into account
    > also possible floating decimal parts.
    > I hope no typo or gross misconception is in it but it seems fine to me.
    > Rebuild lines that the mail viewer may have broken.
    >
    > <script>
    > var n=1234567890.5502;
    >
    > function nFormat(n){
    > //validate
    > if(typeof(parseFloat(n))!="number"){return false;};
    > n+="";
    > //initialize


    // You may want to check if n<0, and remove minus sign.

    sign=n<0 "-":"";
    if(sign){n=n.substring(1)}

    > var begin=0, middle="", tail="";
    > if(n.indexOf(".")>-1){
    > tail=n.substring( n.indexOf(".") );//floating tail first!
    > n=n.substring( 0, n.indexOf(".") );
    > };
    > //RUN
    > for(var i=n.length-3; i>0; i-=3, begin++){
    > middle=","+n.substring(i, i+3)+middle;
    > }
    > //return
    > return n.substring(0, n.length-(middle.length-begin) )+middle+tail;


    // Add minus sign, if any, here.
    // n.length%3 might work here, too.
    // return sign+n.substring(0, n.length%3) + middle+tail;
    // I like your approach, well done.

    Mick

    > }
    >
    > alert( nFormat(n) );
    > </script>
    >
    > I hope this helps
    > ciao
    > Alberto
    > http://www.unitedscripters.com/
    Mick White, Jul 6, 2004
    #17
  18. KsAdmin

    KsAdmin Guest

    Thanks for all the help.
    On top of solving my problem I have got my brain on the right track
    again =)
    so back to work I go

    Josh

    Josh Austin
    System Administrator
    Agent Services of America
    ksadmin NOSPAM @comcast.net
    (remove NOSPAM and the spaces out of my email address to send email)
    KsAdmin, Jul 6, 2004
    #18
  19. KsAdmin

    Alberto Guest

    Yeah Mick I already did that in one of my posts above, the fact is this
    thread gets unexpectedly long lol
    ciao


    "Mick White" <> ha scritto nel messaggio
    news:SqDGc.16215$...
    > Alberto wrote:
    >
    > > Mah the following should work, it's a bit longer for it takes into

    account
    > > also possible floating decimal parts.
    > > I hope no typo or gross misconception is in it but it seems fine to me.
    > > Rebuild lines that the mail viewer may have broken.
    > >
    > > <script>
    > > var n=1234567890.5502;
    > >
    > > function nFormat(n){
    > > //validate
    > > if(typeof(parseFloat(n))!="number"){return false;};
    > > n+="";
    > > //initialize

    >
    > // You may want to check if n<0, and remove minus sign.
    >
    > sign=n<0 "-":"";
    > if(sign){n=n.substring(1)}
    >
    > > var begin=0, middle="", tail="";
    > > if(n.indexOf(".")>-1){
    > > tail=n.substring( n.indexOf(".") );//floating tail first!
    > > n=n.substring( 0, n.indexOf(".") );
    > > };
    > > //RUN
    > > for(var i=n.length-3; i>0; i-=3, begin++){
    > > middle=","+n.substring(i, i+3)+middle;
    > > }
    > > //return
    > > return n.substring(0, n.length-(middle.length-begin) )+middle+tail;

    >
    > // Add minus sign, if any, here.
    > // n.length%3 might work here, too.
    > // return sign+n.substring(0, n.length%3) + middle+tail;
    > // I like your approach, well done.
    >
    > Mick
    >
    > > }
    > >
    > > alert( nFormat(n) );
    > > </script>
    > >
    > > I hope this helps
    > > ciao
    > > Alberto
    > > http://www.unitedscripters.com/
    Alberto, Jul 6, 2004
    #19
  20. KsAdmin <ksadmin > writes:

    > I have a question which has had me stumped for a few days now. I have
    > a form that I add the values of fields together and display the total
    > in a total field. I have the calculations working correctly. My
    > problem is that I would like to change the format of the total from
    > 1234567 to 1,234,567 .


    If your form is being used by people with other nationalities, you should
    consider whether that is a good idea. In, e.g., Danish, the comma is the
    decimal separator, so 12,345 would be read as a little over twelve.

    > Is this possible using javascript?


    It's a simple string manipulation, so yes, it's possible.

    > function calculateTotal(){
    > var
    > fields=Array("life1","life2","life3","life4","life5","life6");


    It's hardly necessary to build an array of such easily constructed
    strings (except perhaps for performance, but this problem is too small
    for performance to be any problem)

    > for(i=0;i<fields.length;i++){
    > str="var
    > val"+i+"=parseInt(document.frmLifeNeed."+fields+".value);";
    > eval(str);


    Using eval is generally not recommended. There are other, simpler,
    faster and safer, methods for doing the same.

    Creating a variable for each field and then adding them later
    is overkill. Just add the value directly to the accumulated total.

    Remember to declare "i" as a local variable, or it will be created
    as a global variable.

    var total = 0;
    var formElems = document.forms['frmLifeNeed'].elements;
    for (var i = 0; i < 6; i++) {
    total += Number(formElems['life'+(i+1)].value);
    }

    > document.frmLifeNeed.total.value = total;


    So, here you need the formatting of "total":
    formElems['total'].value = formatNumber(total)

    Then let's define the "formatNumber" function (there are shorter,
    *perhaps* smarter ways):
    ---
    function formatNumber(n, maxDecimals) {
    maxDecimals = maxDecimals || 16;
    // make sure it is a number
    n = Number(n);
    if (isNaN(n)) { return n; }
    // sign
    var neg = n < 0;
    if (neg) { n = -n; }
    // integral part
    var intPart = Math.floor(n);
    // fractional part
    var fracPart = n - intPart;

    var acc = "";
    if (fracPart) {
    acc = ".";
    var decCount = 0;
    while(fracPart && decCount < maxDecimals) {
    var tmp = fracPart * 10;
    acc += Math.floor(tmp);
    fracPart = tmp % 1;
    decCount++;
    }
    }
    if (!intPart) {
    acc = "0" + acc;
    } else {
    while (intPart >= 1000) {
    var first = intPart%1000;
    var tmp = String(1000 + first).substring(1);
    acc = "," + tmp + acc;
    intPart = (intPart - first)/1000;
    }
    acc = String(intPart) + acc;
    }
    return acc;
    }
    ---

    --
    Lasse Reichstein Nielsen -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Jul 6, 2004
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jeremy
    Replies:
    1
    Views:
    361
    Jim White
    Feb 18, 2004
  2. Monique Y. Mudama
    Replies:
    1
    Views:
    443
    Monique Y. Mudama
    Jun 28, 2005
  3. Badass Scotsman
    Replies:
    1
    Views:
    359
    S. Justin Gengo
    Apr 24, 2006
  4. Vedran

    Presenting calculation results

    Vedran, Sep 10, 2008, in forum: Python
    Replies:
    1
    Views:
    287
    Marco Bizzarri
    Sep 10, 2008
  5. Replies:
    2
    Views:
    181
Loading...

Share This Page