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.

  • $\begingroup$ mathematica.stackexchange.com/a/7872/363 $\endgroup$ – Chris Degnen Aug 6 '18 at 12:36
  • 1
    $\begingroup$ If you are looking for a way to print the numbers, then you can use NumberForm. $\endgroup$ – Sumit Aug 6 '18 at 13:31
  • $\begingroup$ @ChrisDegnen That post is about absolute rounding, not about rounding to a fixed amount of significant digits. $\endgroup$ – Henrik Schumacher Aug 6 '18 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_?Internal`RealValuedNumericQ, 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} *)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.