Re: Formatting Number With Thousands Separator
JRS: In article <290e65a0.04040 80954.740fade@p osting.google.c om>, seen
in news:comp.lang. javascript, rh <codeHanger@yah oo.ca> posted at Thu, 8
Apr 2004 10:54:13 :[color=blue]
>
>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(se ps[0]) < 0) ? seps[0] : "") +"00";
> return "$"+ns.repl ace(/(\d{2})\d*$/i,"$1");
> }
>
>Note that e-formatted n is not checked/handled.[/color]
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.
--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
JRS: In article <290e65a0.04040 80954.740fade@p osting.google.c om>, seen
in news:comp.lang. javascript, rh <codeHanger@yah oo.ca> posted at Thu, 8
Apr 2004 10:54:13 :[color=blue]
>
>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(se ps[0]) < 0) ? seps[0] : "") +"00";
> return "$"+ns.repl ace(/(\d{2})\d*$/i,"$1");
> }
>
>Note that e-formatted n is not checked/handled.[/color]
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.
--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Comment