...

View Full Version : Automatically Format text box with decimals



.netfreak
11-29-2012, 02:03 AM
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>

felgall
11-29-2012, 03:04 AM
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.

Old Pedant
11-29-2012, 03:48 AM
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.



<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>

Old Pedant
11-29-2012, 03:50 AM
So then your function reduces to:


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) );
}

Old Pedant
11-29-2012, 03:54 AM
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:


onkeyup = "this.value = Comma( Number( this.value.replace(/,/g,"") ).toFixed(2) );"

No?

Old Pedant
11-29-2012, 03:59 AM
If you use my prettyNumber function (or rename it if you like) then you could indeed do


<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).

Philip M
11-29-2012, 10:24 AM
<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>

007julien
11-29-2012, 06:56 PM
Regular expressions are usefull for this kind of questions



<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 - !

Philip M
11-29-2012, 08:18 PM
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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum