recipes : programming : Rounding numbers

Problem

You want to round a number up, down, or to some arbitrary interval.

SolutionMATLAB has several functions for peforming such operations. In the following examples x may be a single number of an array.

round(x) %Round to the nearest integer ceil(x) %Round up to the nearest integer floor(x) %Round down to the nearest integer fix(x) %Round towards zero %Round a decimal to 3 significant figures round(4.321143/.001)*0.001 ans = 4.3210 %Round down to the nearest multiple of 5 floor(2342/5)*5 ans = 2340

You need to be wary that rounding numbers to a given number of decimal places can produce odd results due to machine precision issues. e.g:

>> A=round(0.7/0.1)*0.1 A = 0.7000 %Yet it evaluates as false when we do: >> A==0.7 ans = 0 %However it will evaluate as true if we convert to single-precision: >> single(A)==single(0.7) ans = 1