Work

# What Comes Round Goes Round

Rated 3.89 (Ratings: 0)

#### Want more?

• More articles in Code

#### 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 1999fixed 17 jan 2000 by sgd --parseInt properly, substr's properlypermission to reuse freely is granted. lemme know if you use it, ok? */whatplace = parseInt(whatplace,10);  //we want this to be a numeric vardotplace = 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: