Formatting Number With Thousands Separator

D

Douglas

Gday,


How would I format a number so that:

TheValue = 32500

Displays in the TextBox as: $32,500.00



Thanks a lot :)
-Douglas
 
R

Randy Webb

Douglas said:
Gday,


How would I format a number so that:

TheValue = 32500

Displays in the TextBox as: $32,500.00

And if the person viewing the page uses . as a separator instead of ,
and uses , instead of . for the decimal?

But, for a hint, convert your number to a String, reverse the String,
then insert the separators, then reverse it back. And then read the FAQ
to find out how to add the 00 on the end (Its in there).
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
Douglas wrote:

And if the person viewing the page uses . as a separator instead of ,
and uses , instead of . for the decimal?

Does any form of javascript recognise the possibility of a different
decimal separator or the possibility of a thousands separator (except by
added code, of course)?

If so, converting the number 12345.6 to string will allow then to be
determined.

But, for a hint, convert your number to a String, reverse the String,
then insert the separators, then reverse it back. And then read the FAQ
to find out how to add the 00 on the end (Its in there).

There's no need to reverse the string.
<URL:http://www.merlyn.demon.co.uk/js-maths.htm#OutComma>
 
L

Lasse Reichstein Nielsen

Dr John Stockton said:
Does any form of javascript recognise the possibility of a different
decimal separator or the possibility of a thousands separator (except by
added code, of course)?

I can't say that there isn't some application of ECMAScript that doesn't
contain utility functions, but it's not part of ECMAScript, and it's not
in the usual clients.
There's no need to reverse the string.
<URL:http://www.merlyn.demon.co.uk/js-maths.htm#OutComma>

I notice the result -,123 :)

If one only cares about recent versions of Javascript, regular
expressions with lokahead can be used to make it easier:
---
function tsep(n,swap) {
var ts=",", ds="."; // thousands and decimal separators
if (swap) { ts=","; ts="."; } // swap if requested

var ns = String(n),ps=ns,ss=""; // numString, prefixString, suffixString
var i = ns.indexOf(".");
if (i!=-1) { // if ".", then split:
ps = ns.substring(0,i);
ss = ds+ns.substring(i+1);
}
return ps.replace(/(\d)(?=(\d{3})+([.]|$))/g,"$1"+ts)+ss;
}
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
I notice the result -,123 :)

In a section which starts "Note that ThouS is for non-negative integers,
and Comma is for integers.", from function ThouS, the first line of
which was

function ThouS(SS) { var X = "", S = String(SS), L // SS >= 0

so that result demonstrates that the comment is significant.

That line of the results is now marked as comment.
 
D

Dr John Stockton

JRS: In article <070420041803456176%[email protected]>, seen in
I took the challenge and wrote the following. If you find an error, let
me know.
/// This script will format positive money values. Pass it a number

/* !!! */ alert(formatMoney(0.07, "£", ".", ",")) // -> 0.70


FAQ 4.6, IIRC, used that underlying method up to 2001-01-22. It was
replaced. The FAQ section cites a page which includes a section
"Testing" which recommends numbers to try : St Luke: Chapter 10, Verse
37, tail, applies.

Your method degrades badly at sums of $1e21 and up, too.

BTW, the X-Comments line of your header is defective.

Familiarising oneself with a newsgroup FAQ before posting protects
against unnecessary embarrassment.
 
D

Douglas

Gday Dennis :)

thanks very much for your efforts...

While I'm not new to programming, this is probably my first attempt to
modify my own JavaScript.

I have made a couple of minor additions to the code you supplied, and
honestly, didnt have the faintest idea where to start because the syntax /
object model / typing etc are so vastly different from the code I am used to
writing.

Here 'tis... prolly a bit longhand and I'm sure theres more 'efficient' ways
to do the same thing but lets face it its prolly only a couple of cpu cycles
and additionally, those cpu cycles are not run on /my/ server :))

Thanks Again.
-Douglas


/// ///
/// JavaScript FormatCurrency Function - FormatCurrency.js ///
/// ///

/// This script will format positive money values. Pass it a number
/// with or without decimal digits. It will be formatted with the currency,
/// thousands, and decimal symbols passed to it.

/// PASSED PARAMETERS
/// theNumber - the number to be formatted
/// theCurrency - the currency symbol
/// theThousands - the thousands separator
/// theDecimal - the decimal separator

function isThousands(position)
{
if (Math.floor(position/3)*3==position) return true;
return false;
};


function formatMoney (theNumber,theCurrency,theThousands,theDecimal)
{

if (theDecimal==undefined)
{
var theDecimalDigits = "";

} else {

var theDecimalDigits =
Math.round((theNumber*100)-(Math.floor(theNumber)*100));
}

theDecimalDigits= "" + (theDecimalDigits + "0").substring(0,2);

theNumber = "" + Math.floor(theNumber);

var theOutput = theCurrency;

for (x=0; x<theNumber.length; x++)
{

theOutput += theNumber.substring(x, x+1);

if (isThousands(theNumber.length-x-1) && (theNumber.length-x-1!=0))
{
theOutput += theThousands;
};
};

if (theDecimal!=undefined)
{
theOutput += theDecimal + theDecimalDigits;
}

return theOutput;
};












----- Original Message -----
From: "Dennis M. Marks" <[email protected]>
Newsgroups: comp.lang.javascript
Sent: Thursday, April 08, 2004 9:03 AM
Subject: Re: Formatting Number With Thousands Separator
 
R

rh

Lasse Reichstein Nielsen wrote:
If one only cares about recent versions of Javascript, regular
expressions with lokahead can be used to make it easier:
---
function tsep(n,swap) {
var ts=",", ds="."; // thousands and decimal separators
if (swap) { ts=","; ts="."; } // swap if requested

var ns = String(n),ps=ns,ss=""; // numString, prefixString, suffixString
var i = ns.indexOf(".");
if (i!=-1) { // if ".", then split:
ps = ns.substring(0,i);
ss = ds+ns.substring(i+1);
}
return ps.replace(/(\d)(?=(\d{3})+([.]|$))/g,"$1"+ts)+ss;
}

An alternative that doesn't rely on lookahead, and includes
(truncated) $ formatting requested by the OP:

function tsep(n,swap) {
var ns = String(n), seps = [".",","];
if(swap) seps.reverse();
while(/^([^.,]*\d)(\d{3}([.,]|$))/.test(ns)) {
ns = ns.replace(/^([^.,]*\d)(\d{3}([.,]|$))/,"$1"+seps[1]+"$2");
}
ns += ((ns.indexOf(seps[0]) < 0) ? seps[0] : "") +"00";
return "$"+ns.replace(/(\d{2})\d*$/i,"$1");
}

Note that e-formatted n is not checked/handled.

../rh
 
D

Douglas

ok cool

didnt actually notice that problem but thanks for the bugfix :)

what i was trying to do with my addition was (in pseudocode):

if no decimal parameter is passed,
dont display the decimal value
(i suppose it /should/ round at this point? =P)
otherwise
go the whole hog
end if

sometimes i need to call the full formula

ie:
cost per m² = $13.65

but the end result will usually be something like:

overall cost = cost per m² * area = $136,500

so in that case i dont want to include the decimal.



on a second issue, consider the following:

--------------------------------
area cost/m² total
--------------------------------
area1 100 $13.65 $1,365
area2 1000 $14.52 $14,520
area3 10000 $17.49 $174,900
--------------------------------
grand total: $190,785
--------------------------------

the grand total now comes up with NaN (not a number i assume?)

even though the formula reads:

gtotal = parseFloat(area1) + parseFloat(area2) + parseFloat(area3);

not sure if i should be using parseFloat or ParseInt...

as I mentioned i dont have a c/jscript background so some of this is a
little unclear to me.



thanks again for your help :)
-Douglas




----- Original Message -----
From: "Dennis M. Marks" <[email protected]>
Newsgroups: comp.lang.javascript
Sent: Friday, April 09, 2004 6:02 AM
Subject: Re: Formatting Number With Thousands Separator - corrected
 
D

Dr John Stockton

JRS: In article <080420041457482581%[email protected]>, seen in
Lines: 183
... ... ...
There is a bug that I am checking into. If the first digit after the
decimal is zero it drops it.
...

You've been posting here long enough to have learnt how follow-up posts
should be formatted; it's explained in the FAQ.

Answer after what needs to be quoted; signatures almost never need be
reproduced.

See also via below.
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen
in news:comp.lang.javascript said:
An alternative that doesn't rely on lookahead, and includes
(truncated) $ formatting requested by the OP:

function tsep(n,swap) {
var ns = String(n), seps = [".",","];
if(swap) seps.reverse();
while(/^([^.,]*\d)(\d{3}([.,]|$))/.test(ns)) {
ns = ns.replace(/^([^.,]*\d)(\d{3}([.,]|$))/,"$1"+seps[1]+"$2");
}
ns += ((ns.indexOf(seps[0]) < 0) ? seps[0] : "") +"00";
return "$"+ns.replace(/(\d{2})\d*$/i,"$1");
}

Note that e-formatted n is not checked/handled.

The OP did not state that the value would always be integer.

tsep(0.07, true) -> $0.07,00
tsep(2.07, true) -> $2.07,00

If you must re-invent the wheel, please test it adequately; otherwise,
read the FAQ.
 
D

Douglas

Dennis M. Marks said:
Parsing seems to stop at the first non numeric character which is the
dollar sign. You may need to display formatted numbers after
calculations. Maybe keep 2 sets, one formatted and one not. I hope
someone has a better answer. I have never used parseInt or parseFloat
until I just tested it now.

BTW: Post responses at the bottom rather than the top.

No worries :)

upon further consideration, i realised i should probably make the grandtotal
formula like this:

gtotal = (area1 * cost1) + (area2 * cost2) + (area3 * cost3);

rather than summing the results of the calculated fields.

-Douglas
 
R

rh

Dr said:
JRS: In article <[email protected]>, seen
in news:comp.lang.javascript said:
An alternative that doesn't rely on lookahead, and includes
(truncated) $ formatting requested by the OP:

function tsep(n,swap) {
var ns = String(n), seps = [".",","];
if(swap) seps.reverse();
while(/^([^.,]*\d)(\d{3}([.,]|$))/.test(ns)) {
ns = ns.replace(/^([^.,]*\d)(\d{3}([.,]|$))/,"$1"+seps[1]+"$2");
}
ns += ((ns.indexOf(seps[0]) < 0) ? seps[0] : "") +"00";
return "$"+ns.replace(/(\d{2})\d*$/i,"$1");
}

Note that e-formatted n is not checked/handled.

The OP did not state that the value would always be integer.

tsep(0.07, true) -> $0.07,00
tsep(2.07, true) -> $2.07,00

If you must re-invent the wheel, please test it adequately; otherwise,
read the FAQ.

My, I gather we're the sensitive sort ... that must have been your
sandpail I was touching? And I'm sorry that Lasse got you all upset.
:(

Actually, if you understood the body of the code (or had adequately
tested prior to becoming all frosty frothy) you might find that there
was no underlying assumption that the "value would always be
integer.".

I did mistakenly conjecture that there could be internationalization
that would produce a string from a number that had "," as the decimal
separator. Well off the mark, I suppose -- and, yes, I should have
known better -- but I note that your referenced page is prepared to
dynamically adjust to precisely such eventuality.

As to attitude -- try referring to me as "pointy head", as you've
presumed to do to a respondent elsewhere, and a suitably qualified
"foreignicator", or something in that ilk, is highly likely to be
embedded in the response text. All in jest, of course! ;)

../rh
 

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,764
Messages
2,569,567
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top