4

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.

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
Aidan
  • 43
  • 1
  • 3

3 Answers3

2

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} *)
Daniel W
  • 3,416
  • 18
  • 31
2

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}

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
2
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 *)
creidhne
  • 5,055
  • 4
  • 20
  • 28
Luboš Motl
  • 544
  • 4
  • 10