Show a number with specified number of significant digits
Posted
by
dreeves
on Stack Overflow
See other posts from Stack Overflow
or by dreeves
Published on 2011-03-06T04:15:51Z
Indexed on
2011/03/06
8:10 UTC
Read the original article
Hit count: 166
mathematica
|Utilities
I use the following function to convert a number to a string for display purposes (don't use scientific notation, don't use a trailing dot, round as specified):
(* Show Number. Convert to string w/ no trailing dot. Round to the nearest r. *)
Unprotect[Round]; Round[x_,0] := x; Protect[Round];
shn[x_, r_:0] := StringReplace[
ToString@NumberForm[Round[N@x,r], ExponentFunction->(Null&)], re@"\\.$"->""]
(Note that re
is an alias for RegularExpression
.)
That's been serving me well for years. But sometimes I don't want to specify the number of digits to round to, rather I want to specify a number of significant figures. For example, 123.456 should display as 123.5 but 0.00123456 should display as 0.001235.
To get really fancy, I might want to specify significant digits both before and after the decimal point. For example, I might want .789 to display as 0.8 but 789.0 to display as 789 rather than 800.
Do you have a handy utility function for this sort of thing, or suggestions for generalizing my function above?
Related: Suppressing a trailing "." in numerical output from Mathematica
© Stack Overflow or respective owner