In comp.lang.javascript message <2430bcc7-e975-41dc-bbe5-258349ea3bb2@l3
4g2000vba.googlegroups.com>, Tue, 22 Sep 2009 05:02:46, abozhilov
Here you are incorrect.
n = +n; //ToNumber(n) 9.3 in ECMA3
Representing null as zero or undefined as NaN is a failure, in my
opinion, in a general-purpose routine.
What are you mean? Here i don't understand exactly what are you mean
with that.
Your browser has mis-quoted that, and so perhaps it had mis-
displayed it. Try <URL:
www.gum.ru> - but only for amusement.
After your post, and my tests. I have latest version.
Number.format = function(num, fraction)
That's not "plug-compatible" with .toFixed; and ISTM that it must be
called as a method of a number whose value is not used. I'd expect num
not to be in the argument list, and for
to be num = +this ;
It should not be necessary to use "call", IMHO.
if (isNaN(num))
{
return 'NaN';
}
if (1e21 <= Math.abs(num))
{
return '' + num;
}
var end = num % 1,
start = num - end,
f = Math.min(21, fraction),
pow = Math.pow(10, f);
end = Math.round(Math.abs(end) * pow);
if (end == pow)
{
start++;
end = 0;
}
return start + (f > 0 ? '.' + padLeft(end, f, '0') : '');
}
With fraction value between, 0 - 21. If fraction less than 0 will
return results like fraction value equal to 0. If fraction great than
21, results will be like fraction equal 21.
For test cases. And comparing results see:
<URL:
http://213.130.84.45/Number/toFixed.html>
I have adjusted it to fit and put it into
<URL:
http://www.merlyn.demon.co.uk/js-rndg2.htm>. That way I can
automatically test against many inputs, and manually test too. I've not
uploaded it yet; the previous version of the page is dated 2009-04-29.
With some negative inputs, it gives wrong but plausible answers; so
negative inputs need testing for.
If there are no negative inputs, the Math.abs may not be needed?
However, a calculation that, ideally, would give zero may actually,
because of rounding errors, give a small negative number. So that must
be allowed, and be treated as zero.
When a number to be rounded to N places is entered as a literal with a
value exactly half-way between two adjacent N-place numbers, ISTM that
yours and that in the FAQ may round differently. I don't think that is
important.
However, for inputs that are represented exactly by an IEEE Double, the
Standard specifies rounding away from zero, and not Bankers Rounding.
Yours is OK there.
There is one other algorithm on that page, TwoDP in "Satisfactory
Conversions to String", which uses the % operator; and the operator is
used very differently. So, at least as far as this newsgroup goes, you
seem to have a New Method. On the other hand, looking for ++, your
method resembles that of TMoney.
I think toFixed(0) is wrong; it should give a decimal point. If no
point is wanted, one can just Math.round the number.