Sunday, July 26, 2009

Java - Rounding floating point numbers to a certain number of decimal places

Small piece of code to round decimal numbers to specified number of decimal places.
public float Round(float val, int roundOffTo){
float p = (float)Math.pow(10,roundOffTo);
val = val * p;
float tmp = Math.round(val);
return (float)tmp/p;
}

No comments: