Another Rounding algorithm

D

Dr John Stockton

Here's a function for rounding a Number to a String with N decimal
places (padded to M to the left of the decimal point) using an algorithm
which I do not recall seeing elsewhere (though I doubt whether it's
truly new); its parameters match those of StrU in FAQ 4.6 :-

function stru(X, M, N) { // generally for X > -0.5e-N
var int = Math.floor(X)
var frc = ((X-int)+1) * Math.pow(10, N) // or (X%1+1)* ?
frc = String(IntFrc(frc)) // Put chosen rounding algorithm here
var str = (int + +(frc.charAt(0)=="2")) + '.' + frc.substring(1)
if (/[a-z-]/.test(str)) str = String(X) // did not cope: verbatim
return SpcsTo(str, M+1+N) // SpcsTo, M optional
}

If extending leftwards to fixed length M+1+N with SpcsTo is omitted, the
argument N is used only once, and by omitting Math.pow() one can use 1eN
instead.

With function IntFrc(frc) { return Math.round(frc) } , stru
gives the usual sort of rounding.

It, with test code and more words, are in temporary Web page (< 4kB?)
<URL:http://www.merlyn.demon.co.uk/$rnd.htm>, with an IntFrc allowing
currently six forma of "rounding". It needs further consideration and
testing ...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,248
Latest member
MagdalenaB

Latest Threads

Top