By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,784 Members | 1,198 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,784 IT Pros & Developers. It's quick & easy.

Formatting the results of a calculation

P: n/a
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","life 5","life6");
for(i=0;i<fields.length;i++){
str="var
val"+i+"=parseInt(document.frmLifeNeed."+fields[i]+".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)
Jul 23 '05 #1
Share this Question
Share on Google+
22 Replies


P: n/a
Ivo
"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
Jul 23 '05 #2

P: n/a
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" <no@thank.you> 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)
Jul 23 '05 #3

P: n/a
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
Jul 23 '05 #4

P: n/a
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
<mw******@BOGUSrochester.rr.com> 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)
Jul 23 '05 #5

P: n/a
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 NO****@comcast.net> ha scritto nel messaggio
news:9k********************************@4ax.com...
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","life 5","life6");
for(i=0;i<fields.length;i++){
str="var
val"+i+"=parseInt(document.frmLifeNeed."+fields[i]+".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)

Jul 23 '05 #6

P: n/a
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 NO****@comcast.net> ha scritto nel messaggio
news:mu********************************@4ax.com...
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
<mw******@BOGUSrochester.rr.com> 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)

Jul 23 '05 #7

P: n/a
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
Jul 23 '05 #8

P: n/a
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/
Jul 23 '05 #9

P: n/a
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/
Jul 23 '05 #10

P: n/a
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
Jul 23 '05 #11

P: n/a
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" <no****@nospam.nospam>
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)
Jul 23 '05 #12

P: n/a
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 NO****@comcast.net> ha scritto nel messaggio
news:no********************************@4ax.com...
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" <no****@nospam.nospam>
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 intoaccount <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)

Jul 23 '05 #13

P: n/a
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","lif e6");
var total=0;
for(i=0;i<fields.length;i++){
var aval=parseFloat(document.frmLifeNeed[fields[i]].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 NO****@comcast.net> ha scritto nel messaggio
news:no********************************@4ax.com...
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?

Jul 23 '05 #14

P: n/a
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","life 5","life6");

for(i=0;i<fields.length;i++){
str="var
val"+i+"=parseInt(document.frmLifeNeed."+fields[i]+".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
<mw******@BOGUSrochester.rr.com> 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)
Jul 23 '05 #15

P: n/a
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
NO****@comcast.net> 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","life 5","life6");

for(i=0;i<fields.length;i++){
str="var
val"+i+"=parseInt(document.frmLifeNeed."+fields[i]+".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
<mw******@BOGUSrochester.rr.com> 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)
Jul 23 '05 #16

P: n/a
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/

Jul 23 '05 #17

P: n/a
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)
Jul 23 '05 #18

P: n/a
Yeah Mick I already did that in one of my posts above, the fact is this
thread gets unexpectedly long lol
ciao
"Mick White" <mw******@BOGUSrochester.rr.com> ha scritto nel messaggio
news:Sq*******************@twister.nyroc.rr.com...
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/

Jul 23 '05 #19

P: n/a
KsAdmin <ksadmin NO****@comcast.net> 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","life 5","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[i]+".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 - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #20

P: n/a
KsAdmin wrote:
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);

// My mistake, the "getDecimal()" function assumes the argument passed
// to be a Number with decimals.

function getDecimal(val){
val+="";
d=val.indexOf(".");
return d==-1?"":val.substring(d);
}
// This takes care of any Numbers

Mick
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","life 5","life6");

for(i=0;i<fields.length;i++){
str="var
val"+i+"=parseInt(document.frmLifeNeed."+field s[i]+".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
<mw******@BOGUSrochester.rr.com> 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)

Jul 23 '05 #21

P: n/a
Lasse Reichstein Nielsen wrote:

<snip>
---
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 intPart = Math.floor(n);
// fractional part
var fracPart = n - intPart;

The calculation above is problematic, consider:

alert(formatNumber(-10000.555666777,12))

The decimal part is better retrieved by string manipulation. IMVHO.

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

Jul 23 '05 #22

P: n/a
JRS: In article <9k********************************@4ax.com>, seen in
news:comp.lang.javascript, KsAdmin <ksadmin@NOSPAM.?.net> posted at Tue,
6 Jul 2004 13:34:45 :
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","lif e5","life6");
for(i=0;i<fields.length;i++){
str="var
val"+i+"=parseInt(document.frmLifeNeed."+fields[i]+".value);";
eval(str);
}
total=val0+val1+val2+val3+val4-val5
document.frmLifeNeed.total.value = total;
}


Firstly, read the regularly-posted FAQ, and the FAQ notes, carefully on
the subject of newsgroup article formatting; in particular, line
wrapping, quoting, signature separators. And, when you can, the new
parts of the next FAQ issue.

Never use parseInt without a second parameter unless you understand and
require what it may do. For example, what do you expect the result of
parseInt('0042e5') to be? To convert a string value into a number, see
the corresponding FAQ entry; I would use a unary + but others prefer
Number().

Never use eval, except to evaluate an externally-supplied string.

Your routine above is weird; I'm sure it could be done better, but to
make a detailed recommendation would require me to understand your
actual intent.

For the subsequent insertion of commas, see
<URL:http://www.merlyn.demon.co.uk/js-maths.htm#Out>

An Administrator should be employing programmers, not attempting to
emulate one.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://jibbering.com/faq/> JL / RC : FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #23

This discussion thread is closed

Replies have been disabled for this discussion.