Formatting the results of a calculation

K

KsAdmin

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","life5","life6");
for(i=0;i<fields.length;i++){
str="var
val"+i+"=parseInt(document.frmLifeNeed."+fields+".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)
 
I

Ivo

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
 
K

KsAdmin

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

Mick White

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
 
K

KsAdmin

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;

KsAdmin wrote:

<snip>

I would like to change the format of the total from

// 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)
 
A

Alberto

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

Alberto

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

Mick White

Ivo said:
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
 
A

Alberto

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

Alberto

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

KsAdmin

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?
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)
 
M

Mick White

KsAdmin said:
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
 
A

Alberto

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

Alberto

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","life6");
var total=0;
for(i=0;i<fields.length;i++){
var aval=parseFloat(document.frmLifeNeed[fields].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/
 
K

KsAdmin

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","life5","life6");

for(i=0;i<fields.length;i++){
str="var
val"+i+"=parseInt(document.frmLifeNeed."+fields+".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?

KsAdmin wrote:

<snip>

I would like to change the format of the total from

// 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)
 
K

KsAdmin

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
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","life5","life6");

for(i=0;i<fields.length;i++){
str="var
val"+i+"=parseInt(document.frmLifeNeed."+fields+".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?

KsAdmin wrote:

<snip>

I would like to change the format of the total from

// 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)
 
M

Mick White

Alberto said:
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
 
K

KsAdmin

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

Alberto

Yeah Mick I already did that in one of my posts above, the fact is this
thread gets unexpectedly long lol
ciao
 
L

Lasse Reichstein Nielsen

KsAdmin said:
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","life5","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+".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;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top