Skip to page content or Skip to Accesskey List.

Work

Main Page Content

What Comes Round Goes Round

Rated 3.89 (Ratings: 0)

Want more?

  • More articles in Code
 
Picture of sgd

Scott Dexter

Member info

User since: 26 Apr 1999

Articles written: 10

So you're chugging right along in javascript, happy as a lark, until you need to round some numbers to three decimal places. Crap! now what?

This function is your friend. Pass it your value and the decimal place to round to, or 0 to round to an integer.

function RoundToPlace (decimalvalue,whatplace) {

/* written in about 30minutes by sgd@ti3.com, 27 april 1999

fixed 17 jan 2000 by sgd --parseInt properly, substr's properly

permission to reuse freely is granted. lemme know if you use it, ok? */

whatplace = parseInt(whatplace,10); //we want this to be a numeric var

dotplace = decimalvalue.indexOf(".");

var roundplace = dotplace + whatplace;

if (whatplace){ // greater than zero means we want to keep decimals

if (parseInt(decimalvalue.substr(roundplace+1,1),10)>=5) {

/* build our decimal increment. since javascript takes 1/(10^whatplace) and blows it with FP

arithmetic, we'll build it using strings: 1/(10^whatplace) <=> '.' + (whatplace-1)*'0' + '1' */

zeropad = ""

for (i=0;i<whatplace-1;i++) {zeropad +="0";}

decimalincrement = parseFloat("."+zeropad+"1");

return parseFloat(decimalvalue.substr(0,roundplace+1))+decimalincrement;

} else { // return unincremented decimal

return parseFloat(decimalvalue.substr(0,roundplace+1));

}

} else { // we want an integer, test the first decimal place

if (parseInt(decimalvalue.substr(dotplace+1,1),10)>=5){ // return the int + 1

return parseInt(decimalvalue.substr(0,dotplace),10)+1;

} else { // return just the int part, unharmed

return decimalvalue.substr(0,dotplace);

}

}

} // end function RountToPlace

The access keys for this page are: ALT (Control on a Mac) plus:

evolt.org Evolt.org is an all-volunteer resource for web developers made up of a discussion list, a browser archive, and member-submitted articles. This article is the property of its author, please do not redistribute or use elsewhere without checking with the author.