Main Page Content
What Comes Round Goes Round
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.
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 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