JRS: In article <cf********@news2.newsguy.com>, dated Mon, 9 Aug 2004
14:27:16, seen in news:comp.lang.javascript, Matt Kruse
<ne********@mattkruse.com> posted :
Michael Winter wrote: How do I ensure a number has no more than 4 digits and 2
decimalplaces (adds .0 or .00 as necessary) onblur using reg
expressions?Hints or solutions appreciated.
This is partially answered in the group FAQ (it's a good idea to read
it before posting). See <URL:http://jibbering.com/faq/#FAQ4_6>. The
code there add a function to Number objects, called toFixed.
IMO, someone should take the time to write printf() and sprintf() functions
which behave in the 'standard' way. That would be really handy in js, and
instantly useable by most people with a programming background.
Any volunteers? ;)
I've been programming for a number of years, and AFAIR I have never used
a language with printf() or sprintf(). That casts some slight doubt on
your argument, and renders it impossible for me to code such functions
without access to a full and authoritative specification.
However, AISB, highly flexible functions need for implementation a
considerable amount of code (especially in a language which is not
ideally suited to efficient manipulation of string internals), and on a
given Web page or Web site only a small proportion of the flexibility
will usually be used.
In other words, it would be bloatware.
What can reasonably be put into a compiler's library, especially with
smart linking, is quite inappropriate in a scripting language for pages
which are likely to be distributed over slow links - into the boonies,
over the air, etc.
Via the FAQ and by other means one can find a large number of solutions
to the task of rounding a javascript Number to a string with N or 2
decimal places, some of which also format the integer part.
It might be worth examining the allied but distinct question of
"normalising" a String that represents a number, without converting
it to Number - for example converting '123.456' to '+000123.45' or to
' +123.45' or ... .
The necessary parameters seem to be places before the point, places
after, leading zeroes or spaces or not, sign or not.
For simplicity, one would either prohibit excess decimals or specify
truncation towards zero - numeric input strings should be validated
first, to deal with unreasonable input.
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Proper <= 4-line sig. separator as above, a line exactly "-- " (SonOfRFC1036)
Do not Mail News to me. Before a reply, quote with ">" or "> " (SonOfRFC1036)