# Rounding numbers to certain numbers of significant figures

I have code which outputs numbers, for example,(0.2945847, 0.8647834, 1.6*10^-6) and similar. I would like to take these numbers and round them to 4 significant figures, but I can't find a way to do this.

I know N[expr, digits] can round an expression to certain significant figures but it doesn't seem to work with my numbers.

N is implemented such it will never lose precision when the input is already a floating point number (with more significant digits than the second argument of N).

In order to enforce rounding to 4 digits, use SetPrecision:

a = {0.2945847, 0.8647834, 1.6*10^-6};
SetPrecision[a, 4]


{0.2946, 0.8648, 1.600*10^-6}

Below is the function I use for rounding to p significant figures. I played around with a few methods, but settled on MantissaExponent on the philosophy of using built-in functions whenever possible.

NTo[x_?InternalRealValuedNumericQ, p_Integer?Positive] :=
Function[{m, e}, N[Round[m 10^p]10^(e - p)]] @@ MantissaExponent[x];

NTo[z_?NumericQ, p_Integer?Positive] := Complex[NTo[Re[z], p], NTo[Im[z], p]];

NTo[p_Integer?Positive][x_] := NTo[x, p];


Example usage:

NTo[4] /@ {0.2945847, 0.8647834, 1.6*10^-6}

(* {0.2946, 0.8648, 1.6*10^-6} *)
`