Tuesday, June 29, 2010

Truncating or rounding off a decimal value/array to user-specified number of decimal places

Sometimes, you want to truncate long floating point numbers to keep just the first few digits following the decimal point. The easy way to do this is

xr = round(x/n) * n

where
x = original floating point number
n = 10^(-[number of digits after decimal])

e.g. x=1.5673454, n = 0.01 (2 digits after decimal point)
xr = 1.57