From: Garrett Smith on
Dr J R Stockton wrote:
> In comp.lang.javascript message <4bb130fb$0$286$14726298(a)news.sunsite.dk
>> , Mon, 29 Mar 2010 23:00:03, FAQ server <javascript(a)dotinternet.be>
> posted:
>> -----------------------------------------------------------------------
>> FAQ Topic - How do I format a Number as a String with
>> exactly 2 decimal places?
>> -----------------------------------------------------------------------
>>
>> When formatting money for example, to format 6.57634 to
>> 6.58, 6.5 to 6.50, and 6 to 6.00?
>>
>> Rounding of x.xx5 is uncertain, as such numbers are not
> ^ most
>> represented exactly.

What such numbers?

>
>
>> ECMAScript Ed. 3.0 introduced ` Number.prototype.toFixed `.
>> There are bugs in JScript's implementation with certain numbers,
>> for example ` 0.07 `.
>
> "JScript" needs a "Microsoft", since otherwise it may be taken as a
> typo.
>

"Microsoft JScript" would be redundant.

> There is no problem with 0.07.toFixed(2) (review Subject line) and
> so the example should be 0.007.
>

There is a problem with 0.07.toFixed(1), though as you point out, that
is only one decimal place. The example can be changed to 0.007, which is
also a problem, and which is more relevant to the question.

>
>> Function ` numberToFixed ` returns accurate results that are
>> consistent across implementations where ` n > 0 `.
> ???????????????
> That limitation should be inappropriate. If it is, give an example
> which can be fixed.
>

That line can be removed.

>
> It would be better not to use the identifier "n" in both sub-functions,
> as it does not represent exactly the same thing. Use "m" in one case.
>

`positiveNum`?

| function toUnsignedString(positiveNum, digits) {
| var t, s = Math.round(positiveNum * Math.pow(10, digits)) + "",
| start, end;
| if (/\D/.test(s)) {
| return "" + positiveNum;
| }
| s = padLeft(s, 1 + digits, "0");
| start = s.substring(0, t = (s.length - digits));
| end = s.substring(t);
| if(end) {
| end = "." + end;
| }
| return start + end; // avoid "0."
| }

--
Garrett
comp.lang.javascript FAQ: http://jibbering.com/faq/