From: Dr J R Stockton on
In comp.lang.javascript message <T$T1ZKScjRLMFwj8(a)invalid.uk.co.demon.me
rlyn.invalid>, Thu, 1 Jul 2010 23:38:20, Dr J R Stockton
<reply1026(a)merlyn.demon.co.uk> posted:

>
>It is <URL:http://www.merlyn.demon.co.uk/js-maths.htm#BEA>, once seen to
>have been debugged and once the comment is adjusted so that a sufficient
>number of people can understand the code. It uses the method that one
>would use with pencil and paper.


That seems completed. For radix 10, it agrees with parseFloat 99.98% of
the time in all browsers, otherwise differing only slightly. No
exponents. AFAICS, it should always be exact, rounding up for 0.5 LSB &
above.



function refParseFixed(IN, Rdx) { var Tmp, Sgn = +1, J = 0, Scale
Digits = "0123456789abcdefghijklmnopqrstuvwxyz"
Tmp = IN.charAt(0)
if (Tmp == "-" || Tmp == "+") { J = 1
if (Tmp == "-") Sgn = -1 }

var Num = Int = [], Frc = [], K = IN.length, Cy = true, Bin = []
while (J < K) { Tmp = IN.charAt(J++)
if (Tmp == "." && Num == Int) { Num = Frc ; continue }
Tmp = Digits.indexOf(Tmp.toLowerCase())
if (Tmp < 0 || Tmp >= Rdx) break
if (Tmp > 0) Cy = false
Num.push(Tmp) } // arrays now hold digit Numbers
if (Cy) return Sgn*0 // Zero (otherwise loops forever)

// Process integer part :
while (J = Int.length) { // not ==
for (K=0, Cy=0 ; K<J ; K++) {
Tmp = Cy * Rdx + Int[K] ; Cy = Tmp % 2 ; Int[K] = (Tmp-Cy) / 2 }
Bin.push(Cy)
while (Int[0] == 0) Int.shift() }
Bin.reverse()

while (Bin.length && Bin[0]==0) Bin.shift() // Omit any ldg zeroes
J = Bin.length - 54 ; Scale = 0.5 ; while (--J >= 0) Scale /= 2

// Process fractional part :
while (Bin.length < 54) { Cy = 0 ; K = Frc.length
while (K--) {
Tmp = Frc[K] * 2 + Cy ; Cy = +(Tmp>=Rdx) ; Frc[K] = Tmp % Rdx }
if (Bin.length || Cy == 1) Bin.push(Cy)
Scale *= 2 }

Bin[52] += Bin[53] // Rounding: now use Bin[0..52]

// Evaluate Bin and scale it :
for (J = 0, Num = 0 ; J < 53 ; J++) { Num *= 2 ; Num += Bin[J] }
return Sgn * Num / Scale } // end refParseFixed

--
(c) John Stockton, nr London, UK. ?@merlyn.demon.co.uk Turnpike v6.05 IE 7.
Web <URL:http://www.merlyn.demon.co.uk/> - FAQish topics, acronyms, & links.
Command-prompt MiniTrue is useful for viewing/searching/altering files. Free,
DOS/Win/UNIX now 2.0.6; see <URL:http://www.merlyn.demon.co.uk/pc-links.htm>.