From: Gavin Kistner Date: 2005-11-01T23:36:36+09:00 Subject: Re: Newbie: How to format a number to always show two decimals? --Apple-Mail-4-77238386 Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset=MACINTOSH; delsp=yes; format=flowed On Oct 31, 2005, at 5:41 PM, David A. Black wrote: > Aside to Phrogz: is that left over from a game of code golf?? :-) LOL. No, before I grokked sprintf, I needed the round_to =20 functionality. That's a port of the Number.toFixed algorithm from =20 section 15.7.4.5 of the ECMAScript (ECMA-262) specs: 15.7.4.5 Number.prototype.toFixed (fractionDigits) Return a string containing the number represented in fixed-point =20 notation with fractionDigits digits after the decimal point. If =20 fractionDigits is undefined, 0 is assumed. Specifically, perform the =20 following steps: 1. Let =C4 be ToInteger(fractionDigits). (If fractionDigits is =20 undefined, this step produces the value 0). 2. If =C4 < 0 or =C4 > 20, t hrow a RangeError exception. 3. Let x be this number value. 4. If x is NaN, return the string "NaN". 5. Let s be t he empty string. 6. I f x =B3 0, go to step 9. 7. Let s be "-". 8. Let x =3D =D0x. 9. I f x =B3 10^21, let m =3D ToString(x) and go to step 20. 10. Let n be an integer for which the exact mathematical value of n =D6 =20= 10^=C4 =D0 x is as close to zero as possible. If there are two such n, =20= pick t he larger n. 11. I f n =3D 0, let m be the string "0". Otherwise, let m be the =20 string consisting of the digits of the decimal representation of n =20 (in order, with no leading zeroes). 12. If =C4 =3D 0, go to step 20. 13. Let k be the number of characters in m. 14. If k > =C4, go to step 18. 15. Let z be the string consisting of =C4 +1=D0k occurrences of the =20 character =D40=D5. 16. Let m be the concatenation of strings z and m. 17. Let k =3D =C4 + 1. 18. Let a be the first k=D0=C4 characters of m, and let b be the =20 remaining =C4 characters of m. 19. Let m be the concatenation of the three strings a, ".", and b. 20. Return the concatenation of the strings s and m. --Apple-Mail-4-77238386--