Forum Moderators: open

Message Too Old, No Replies

Javascript Numbers Help

         

watermark

6:13 pm on Jan 28, 2005 (gmt 0)

10+ Year Member



Hi All,

I have a simple "calculator" on a client site set up to figure out savings he can provide to his clients. Its very simple and works, but is there any way to tell the script to include commas so that instead of 100000 it reads 100,000?

Here is the current script:

<SCRIPT language = JavaScript>

function calculate() {
A = document.frm.inv.value
B = document.frm.fd.value
C = document.frm.bo.value
A = Number(A)
B = Number(B)
C = Number(C)
D = (B + C)
document.frm.tc.value = D
E = (D / A * 100)
document.frm.poi.value = E
F = (E - 3.25)
document.frm.subt.value = F
H = (A * F)
document.frm.savings.value = H
}
</SCRIPT>

Bernard Marx

9:18 pm on Jan 28, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I was about to knock up a function to do this, then I realised that there must be a good few around already. This one was the first that came up after Googling
"javascript number formatting commas"

[mredkj.com ]

watermark

9:45 pm on Jan 28, 2005 (gmt 0)

10+ Year Member



Hi Bernard,

Thanks for answering. I actually came across that same tutorial in the time since I posted this message...however, I am a JS newbie and dont know how to implement it into my current script/layout.

It took me long enough to get the current script working properly. Could i just cut and paste that coding and place it in with the current script and it will work? Or, do I have to customize it to work with what I already have?

JG

Bernard Marx

10:07 pm on Jan 28, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just use the function (with a little credit). You could make a small amendment to suit though, so you don't have to call it with all the commas etc.

Change the function so that it only receives one argument, but with the separators hard-coded:

function addSeparatorsNF(nStr)
{
var inD='.',outD='.',sep=',';
nStr += '';
....

- that's assuming you want comma separators, and a dot decimal.

The function will accept both strings and numbers, so you can just put your results straight in.

One thing the function doesn't do is turn the figure into a standardised decimal currency format, ie:

100002.234 --> 100,002.234 not 100,002.23

Do you need to do that?