# 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.

• mathematica.stackexchange.com/a/7872/363 Aug 6, 2018 at 12:36
• If you are looking for a way to print the numbers, then you can use NumberForm. Aug 6, 2018 at 13:31
• @ChrisDegnen That post is about absolute rounding, not about rounding to a fixed amount of significant digits. Aug 6, 2018 at 13:40

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} *)

NsigFig[x_, digits_] :=
If[x == 0, 0., Round[x, 0. + 10^(Round[Log[10, x] - digits + 0.5])]]


Try:

NsigFig[3.1415926, 4]
(* 3.142 *)
`