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) 22 1746
"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
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)
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
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)
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)
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)
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
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/
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/
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
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)
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)
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?
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)
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)
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/
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)
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/
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.'
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)
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; } ---
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. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: maceo |
last post by:
I have some code that extracts the data from a table and performs a
calculation (total time) on one of the columns.
Here is the code:
<?php
/* Database connection */
|
by: David Sharp |
last post by:
Once I've converted my floats to chars using STR, is there an easy way
to put commas in separating the thousands.
i.e. convert
53000000.12
to
53,000,000.12
I'm thinking I'll have to do it...
|
by: Eddy Bee |
last post by:
Hi there,
I'm encountering an inexplicable problem with page formatting in
reports. Here's the easiest way to explain it:
The Detail section of my report contains two elements:
And let's...
|
by: Bjørn Augestad |
last post by:
Below is a program which converts a double to an integer in two
different ways, giving me two different values for the int. The basic
expression is 1.0 / (1.0 * 365.0) which should be 365, but one...
|
by: pavan |
last post by:
See the following code :
#include <iostream>
using namespace std;
float f1 = 1.0e+6;
// This function just returns f1.
float value1()
|
by: Coleen |
last post by:
Hi all :-)
I have a weird formatting problem with an HTML table that I am populating using VB.Net and HTML.
Here is the snippet of code for the cell I'm trying to format:
Dim...
|
by: Jimmy |
last post by:
Is there a way to force access to wait a specified time before making a
calculation?
On my report there is a subreport with a number of calculation on it. One if
which is a count of certain...
|
by: egrill |
last post by:
I need assistance on how I can keep the results of a calculated field as part of a record. Each time I use the form I loose the previous calculation. I can set-up the form calculation but want to...
|
by: colin |
last post by:
Hi,
Ive got a difference in results depending on wether I run my app
in the debugger, or run it seperatly (or with <ctrl-f5>)
the results in the debugger seem to be more correct, although
the...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
| |