3
$\begingroup$

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.

$\endgroup$
3
  • $\begingroup$ mathematica.stackexchange.com/a/7872/363 $\endgroup$ Aug 6, 2018 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, 2018 at 13:31
  • $\begingroup$ @ChrisDegnen That post is about absolute rounding, not about rounding to a fixed amount of significant digits. $\endgroup$ Aug 6, 2018 at 13:40

3 Answers 3

1
$\begingroup$

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}

$\endgroup$
1
$\begingroup$

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} *)
$\endgroup$
0
$\begingroup$

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

Try: NsigFig[3.1415926,4]

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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