Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-29-2012, 01:03 AM   PM User | #1
.netfreak
New to the CF scene

 
Join Date: Nov 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
.netfreak is an unknown quantity at this point
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>
.netfreak is offline   Reply With Quote
Old 11-29-2012, 02:04 AM   PM User | #2
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,530
Thanks: 0
Thanked 503 Times in 494 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
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/
felgall is offline   Reply With Quote
Old 11-29-2012, 02:48 AM   PM User | #3
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 11-29-2012, 02:50 AM   PM User | #4
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 11-29-2012, 02:54 AM   PM User | #5
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 11-29-2012, 02:59 AM   PM User | #6
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
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.
Old Pedant is offline   Reply With Quote
Old 11-29-2012, 09:24 AM   PM User | #7
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,102
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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>
__________________

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.

Last edited by Philip M; 11-29-2012 at 11:03 AM.. Reason: Improved
Philip M is offline   Reply With Quote
Old 11-29-2012, 05:56 PM   PM User | #8
007julien
Regular Coder

 
Join Date: May 2012
Location: France
Posts: 122
Thanks: 0
Thanked 18 Times in 16 Posts
007julien is an unknown quantity at this point
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..
007julien is online now   Reply With Quote
Old 11-29-2012, 07:18 PM   PM User | #9
Philip M
Supreme Master coder!

 
Philip M's Avatar
 
Join Date: Jun 2002
Location: London, England
Posts: 17,102
Thanks: 197
Thanked 2,421 Times in 2,399 Posts
Philip M has a spectacular aura aboutPhilip M has a spectacular aura aboutPhilip M has a spectacular aura about
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.
__________________

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.

Last edited by Philip M; 11-30-2012 at 07:39 AM..
Philip M is offline   Reply With Quote
Reply

Bookmarks

Tags
asp.net, java script, jquery

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 12:47 PM.


Advertisement
Log in to turn off these ads.