H
Hal Rosser
From previous postings, I assume that the round method of the Math object
leaves too much to chance, and should not be used. It has also been
suggested that rounding be done by converting the number to string - then
use string manipulation.
So - with that in mind, please check the validity of the following code:
// the args: n is the number to round, and x the number of places
function roundNtoXplaces(n, x){
// move the decimal over x places
n = n * (Math.pow(10, x));
// coerce the number to a string
n = "" + n;
// split the string at the new decimal place
var numParts = n.split(".");
// if the decimal part would come after "5" if sorted alphabetically,
// then add 1 to the int part
if (numParts[1]+"" >= "5"){
numParts[0]++;
}
//coerce the number back to a string
// This string contains the numbers we will be returning
numParts[0] += "";
//get the length of the string
var len = numParts[0].length;
// since we moved the decimal over to work with it, now we put it back
// intPart is the part before the decimal
var intPart = numParts[0].substr(0, (len - x));
//decimalPart is the part of the string after the decimal
var decimalPart = numParts[0].substr( len - x, x );
var outString =intPart + "." + decimalPart;
return outString;
leaves too much to chance, and should not be used. It has also been
suggested that rounding be done by converting the number to string - then
use string manipulation.
So - with that in mind, please check the validity of the following code:
// the args: n is the number to round, and x the number of places
function roundNtoXplaces(n, x){
// move the decimal over x places
n = n * (Math.pow(10, x));
// coerce the number to a string
n = "" + n;
// split the string at the new decimal place
var numParts = n.split(".");
// if the decimal part would come after "5" if sorted alphabetically,
// then add 1 to the int part
if (numParts[1]+"" >= "5"){
numParts[0]++;
}
//coerce the number back to a string
// This string contains the numbers we will be returning
numParts[0] += "";
//get the length of the string
var len = numParts[0].length;
// since we moved the decimal over to work with it, now we put it back
// intPart is the part before the decimal
var intPart = numParts[0].substr(0, (len - x));
//decimalPart is the part of the string after the decimal
var decimalPart = numParts[0].substr( len - x, x );
var outString =intPart + "." + decimalPart;
return outString;