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 9 of 9
  1. #1
    New to the CF scene
    Join Date
    Nov 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Automatically Format text box with decimals

    Hie all,
    I have two text boxes in aspx page which automatically add commas when user enters number. These text boxes are added to third text box. It works fine with commas. But I want all text boxes to automatically format to two decimals including comma (Ex : 1,345.00(instead of 1,345) + 3,456.00(instead of 3,456) = 4,801.00(instead of 4,801)) .
    I got this code which works fine to add text boxes and show result with comma but it does not automatically include two decimal points. Please help me as I am newbie in JavaScript. Thanks in advance.
    <%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm8.aspx.cs" Inherits="Application.WebForm8" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script type="text/javascript" language="javascript">
    function Comma(Num) { //function to add commas to textboxes
    Num += '';
    Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
    Num = Num.replace(',', ''); Num = Num.replace(',', ''); Num = Num.replace(',', '');
    x = Num.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1))
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
    return x1 + x2;

    }
    function sumCalc() // function to remove comma and then add to third textbox
    {
    var txt1 = document.getElementById('<%=tb1.ClientID %>').value.replace(/,/g, "");
    var txt2 = document.getElementById('<%=tb2.ClientID %>').value.replace(/,/g, "");
    var txt3 = document.getElementById('<%=tb3.ClientID %>').value = Comma(parseFloat(txt1) + parseFloat(txt2));

    }
    </script>
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:TextBox ID="tb1" runat="server" onkeyup = "javascript:this.value=Comma(this.value);" ></asp:TextBox>
    <asp:TextBox ID="tb2" runat="server" onkeyup = "javascript:this.value=Comma(this.value);"></asp:TextBox>
    <br />
    <asp:Label ID="Label1" runat="server" Text="Result"></asp:Label>
    <br />
    <asp:TextBox ID="tb3" runat="server" onfocus="javascript:sumCalc();" ></asp:TextBox>
    <br />
    <br />
    <br />
    </asp:Content>

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,639
    Thanks
    0
    Thanked 649 Times in 639 Posts
    add .tofixed(2) to the end of the values

    eg.

    onkeyup = "this.value=Comma(this.value).toFixed(2);"


    Note that it is not necessary to apply a label in front of most JavaScript statements - the exceptions are inside of select statements and nested loops where you want to define which loop a break statement is breaking out of.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,437
    Thanks
    75
    Thanked 4,372 Times in 4,337 Posts
    Okay... For starters, you can *NOT* add those values while they are strings! They *must* be converted to numbers. So the function getNumber in the code below will do that. It will do its best to convert a string to a number. It removes all non-numeric characters from the string and then attempts the conversion.

    And then I fixed your Commas junky code (which never even attempted to ensure that the string being passed had a decimal point, and never attempted to convert a number being passed to add the decimal point!) to make sure that it *CAN* act on the value you give it.

    Oh, and you will notice that the incredibly ugly multiple calls to replace are gone.

    Code:
    <script>
    function getNumber( fromText )
    {
        fromText = String(fromText);
        var n = fromText.replace(/[^\d\.\-]/g, "" ); // zap all but digits,period,minus
        n = Number( n ); 
        if ( isNaN(n) ) { n = 0; } // or any other default value you want to use!! 
        return n;
    }
    
    function prettyNumber( num ) //function to add commas to *NUMBERS* or *NUMERIC TEXT*
    {
        num = getNumber( num ); // ensure we really have a number
        num = num.toFixed(2); // and then ensure it's a string with 2 digits after decimal point
    
        x = num.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1))
        {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }
    
    // this part is just to demo that it works:
    var d1 = "$993,338.27";
    var d2 = "$18,771.99";
    
    var sum = getNumber(d1) + getNumber(d2);
    
    var prettySum = prettyNumber( sum );
    
    alert( prettySum );
    </script>
    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.

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,437
    Thanks
    75
    Thanked 4,372 Times in 4,337 Posts
    So then your function reduces to:
    Code:
    function sumCalc() // function to remove comma and then add to third textbox
    {
        var txt1 = document.getElementById('<%=tb1.ClientID %>').value;
        var txt2 = document.getElementById('<%=tb2.ClientID %>').value;
        document.getElementById('<%=tb3.ClientID %>').value = 
            prettyNumber( getNumber(txt1) + getNumber(txt2) );
    }
    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! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,437
    Thanks
    75
    Thanked 4,372 Times in 4,337 Posts
    Quote Originally Posted by felgall View Post
    add .tofixed(2) to the end of the values

    onkeyup = "this.value=Comma(this.value).toFixed(2);"
    Ummm...I don't think so!

    Comma(this.value) *will* convert this.value to a string, with commas in it.

    And a string does NOT have a toFixed method.

    At best, you could do:
    Code:
    onkeyup = "this.value = Comma( Number( this.value.replace(/,/g,"") ).toFixed(2) );"
    No?
    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.

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,437
    Thanks
    75
    Thanked 4,372 Times in 4,337 Posts
    If you use my prettyNumber function (or rename it if you like) then you could indeed do
    Code:
    <asp:TextBox ID="tb1" runat="server" onkeyup="this.value=prettyNumber(this.value);" />
    The need/desire to put "javascript:" into event handlers is pretty long obsolete.

    The ONLY reason I could see to do so would be if you also had some VBScript code in your web page (in which case the page will only work in MSIE, but that's another story).
    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.

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,984
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Code:
    <input type = "text" name = "num" id = "num" onkeyup = "addCommas(this.value)" onblur = "finalise(this.value)"><br><br>
    
    <script type = "text/javascript">
    
    function addCommas(nStr) {
    nStr = nStr.replace(/[^0-9\.]\-/g,"");  // strip non-numeric
    nStr = nStr.replace(/(.+)\-/,"$1");  // minus sign only as first character
    nStr = nStr.replace(/(\..*)\./,"$1");  // block multiple decimal points
    
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
    nStr = nStr.replace(rgx, '$1,$2');
    }
    nStr = nStr.replace(/(\.\d\d)\d+/, "$1");  // two decimal places max
    document.getElementById('num').value = nStr;
    }
    
    function finalise(nStr) {
    if (nStr == "") {return false}
    if (nStr.charAt(0) == ".") {nStr = "0" + nStr};  // add 0 before leading decimal point
    nStr = nStr.replace(/\.$/,"");  // strip final decimal point
    if (nStr.indexOf('.') == -1) {  // if whole number add .00
    nStr = nStr + ".00";
    }
    nStr = nStr.replace(/(\.\d)$/,"$10");  // if only one DP add another 
    document.getElementById("num").value = nStr;
    }
    
    </script>
    Last edited by Philip M; 11-29-2012 at 11:03 AM. Reason: Improved

    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.

  • #8
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    224
    Thanks
    0
    Thanked 32 Times in 30 Posts
    Regular expressions are usefull for this kind of questions

    Code:
    <script type="text/javascript">
    Number.prototype.toMonetaryString=function(){
    	var n=this.toFixed(2); 
    	return n.replace(/(\d)(?=(\d{3})+\b)/g,'$1,'); // with comma(s) separator
    }
    String.prototype.fromMonetaryToNumber=function(){
    	return +this.replace(/[^\d\.\+-]+/g,'');
    }
    
    // use 
    var i=12345678,j;
    alert(j=i.toMonetaryString()); // '12,345,678.00'
    alert(j.fromMonetaryToNumber())// 12345678
    We replace all digits, followed by a multiple of three digits and a word boundary, by this digit and a comma. Conversely, we keep any digits, points and signs + and - !
    Last edited by 007julien; 11-29-2012 at 06:20 PM.

  • #9
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,984
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by 007julien View Post
    Regular expressions are usefull for this kind of questions
    As we often say, there are often many different ways to skin a cat! Yours is one of the neatest.

    But the OP wants a script which automatically add commas when user enters number.
    Last edited by Philip M; 11-30-2012 at 07:39 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.


  •  

    Tags for this Thread

    Posting Permissions

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