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 5 of 5
  1. #1
    Regular Coder
    Join Date
    Oct 2011
    Posts
    116
    Thanks
    19
    Thanked 1 Time in 1 Post

    Problem in Addition

    Dear Experts

    I have following codes, it works fine to sum. but when I enter these values
    2100.49+100.20 then it says 2,200.6,899,999,999,996 insted of 2,200.69. How to overcome this problem. Please help

    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
    
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <meta name="language" content="english">
    <meta http-equiv="Content-Style-Type" content="text/css">
    
    <title>Numeric Textbox Sample</title>
    
    <style type="text/css">
    #box1 {width:200px;height:170px;border:1px solid green;background:#e3eeff;padding-top:20px;}
    
    .button {width:100px;margin-top:0px;}
    
    body {
    margin:0;
    margin-top:100px;
    }
    </style>
    
    <script language="javascript">
    
    function validate(evt)
    {
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    var backslsh = key;
    var chck = String.fromCharCode( key );
    
    var regex = /[0-9]|\./;
    if( !regex.test(chck) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
    }
    }
    
    
    function addCommas(nStr)
    {
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '.00';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2')
    }
    return x1 + x2;
    }
    
    
    function fncSum2()
    {
    var amount1=form2.text1.value;
    var amount2=form2.text2.value;
    var a = amount1.replace(/[^0-9\.]/g,"");
    var b = amount2.replace(/[^0-9\.]/g,"");
    var nStr = (Number(a) + Number(b)).toString();
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1,$2');
    }
    //nStr = "$" + nStr; // if $ prefix required
    if (nStr.indexOf('.') == -1) {  // if whole number add .00
    nStr = nStr + ".00"
    }
    nStr = nStr.replace(/(\.\d)$/,"$10");  // if only one DP add another 0
    
    return nStr
    }
    
    </script>
    
    </head>
    
    <body onload="form2.text1.focus()" >
    <center>
    <p>Enter 2100.49 in Amount</p>
    <p>Enter 100.20 in Tax</p>
    <p> and press + button<br>
    It shows 2,200.6,899,999,999,996<br>
    but I need 2,200.69</p>
    
    </p>
    <div id="box1">
    <form name=form2>
    <table width="100%" border="0" cellpadding="0" cellspacing="0">
    <tr><td>Amount</td>
    
    <td><input type=text name=text1 size=15 value="" onkeypress='validate(event)' onfocus="this.select
    
    ()" onblur="form2.text1.value=addCommas(form2.text1.value)" > </td></tr> 
    
    <tr><td>Tax</td> <td><input type=text name=text2 size=15 value="" onkeypress='validate(event)' 
    
    onblur="form2.text2.value=addCommas(form2.text2.value)"></td></tr> 
    <tr><td>Result</td><td><input type=text name=text3 size=15 value="" disabled></td></tr>
    
    </table>
    <hr>
    <input class="button" type=button name=command1 value="+" onclick="form2.text3.value=fncSum2()"><br>
    
    <input class="button" type=button name=command8 value="Focus" onclick="form2.text1.select
    
    ()";"form2.text1.focus()"><br>
    <input class="button" type=reset name=command9 value="Reset">
    
    </form>
    </div>
    
    </center>
    </body>
    </html>

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    This goes on and on and on. If you placed some alerts in the code at strategic intervals you would see what is wrong yourself.

    The problem arises because of the binary representation of decimal numbers may not be exact after conversion to a string and back again, so 2100.49+100.20 becomes = 2200.689999999996.

    Change
    var nStr = (Number(a) + Number(b)).toString();
    to
    var nStr = (Number(a) + Number(b)).toFixed(2);


    "Too often the strong silent man is silent because he does not know what to say, and is reputed strong only because he has remained silent." - Winston Churchill (1874-1965)

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    tqmd1 (12-28-2011)

  • #3
    Regular Coder
    Join Date
    Oct 2011
    Posts
    116
    Thanks
    19
    Thanked 1 Time in 1 Post
    Quote Originally Posted by Philip M View Post
    This goes on and on and on.
    This made me laugh.

    Thanks sir, the problem is solved but a new problem has just been arised.

    How to force textbox to accept only 2 digits after decimal point

    I want my textbox to accept this format #,###,###.##

    Instead of #,###,###.###

    Thanks

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,438
    Thanks
    75
    Thanked 4,372 Times in 4,337 Posts
    Does it really matter? Suppose the user entered 37.330 The additional 0 does nothing.

    But yes, you could disallow more than 2 digits after a decimal point. Do you need to do it *AS* the person is typing in the number or is it okay to do it when they are finished entering the number?

    And by the way, JavaScript will *NOT* convert strings with commas in them to numbers, period. So you'll have to strip out the commas before using the Number() code that Philip showed you.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,982
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by tqmd1 View Post
    This made me laugh.

    Thanks sir, the problem is solved but a new problem has just been arised.

    How to force textbox to accept only 2 digits after decimal point

    I want my textbox to accept this format #,###,###.##

    Instead of #,###,###.###
    Well, it is making me cry! I have a suggestion - have you considered learning Javascript?

    Your users must enter numbers (without commas) into the textbox, and these are automatically formatted onblur into strings with commas. You still seem uncertain about this.

    To restrict input to 2 decimal places:-

    Code:
    <script type = "text/javascript">
    
    function only2DP(which){
    var str = which.value;
    str = str.replace(/[^0-9\.]/g,"");
    var pos = str.indexOf(".");
    if (pos > -1) {
    str = str.substring(0, pos+3);
    }
    which.value = str;
    }
    
    </script>
    
    <input name="text1" id = "text1" size = "15" maxlength = "15"  onkeyup="only2DP(this);">
    Note:- use onkeyup, not onkeypress.

    You will need to incorpoarate this code into your existing functions. As I see it it replaces you existing validate() function.

    Quote Originally Posted by Old Pedant View Post
    And by the way, JavaScript will *NOT* convert strings with commas in them to numbers, period. So you'll have to strip out the commas before using the Number() code that Philip showed you.

    You have come rather late to the party. That is what
    Code:
    var amount1=form2.text1.value;
    var amount2=form2.text2.value;
    var a = amount1.replace(/[^0-9\.]/g,"");
    var b = amount2.replace(/[^0-9\.]/g,"");
    var nStr = (Number(a) + Number(b)).toString();
    does.
    Last edited by Philip M; 12-28-2011 at 09:23 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    Posting Permissions

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