显示具有指定有效位数的数字

时间:2011-03-06 04:15:51

标签: wolfram-mathematica utilities

我使用以下函数将数字转换为字符串以供显示(不要使用科学记数法,不要使用尾随点,指定圆形):

(* 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@"\\.$"->""]

(请注意,reRegularExpression的别名。)

多年来,我一直很好。 但有时我不想指定要舍入的位数,而是我想指定一些有效数字。 例如,123.456应显示为123.5,但0.00123456应显示为0.001235。

为了得到真正的幻想,我可能想要在小数点之前和之后指定有效数字。 例如,我可能希望.789显示为0.8但是789.0显示为789而不是800.

对于这类事情你有一个方便的实用功能,还是上面概括我的功能的建议?

相关:Suppressing a trailing "." in numerical output from Mathematica

更新:我在这里尝试询问这个问题的一般版本:
https://stackoverflow.com/questions/5627185/displaying-numbers-to-non-technical-users

3 个答案:

答案 0 :(得分:5)

dreeves,我想我终于理解了你想要的东西,而且你已经拥有它了。如果没有,请再次尝试解释我错过的内容。

shn2[x_, r_: 0] := 
 StringReplace[
  ToString@NumberForm[x, r, ExponentFunction -> (Null &)], 
  RegularExpression@"\\.0*$" -> ""]

测试:

shn2[#, 4] & /@ {123.456, 0.00123456}
shn2[#, {3, 1}] & /@ {789.0, 0.789}
shn2[#, {10, 2}] & /@ {0.1234, 1234.}
shn2[#, {4, 1}] & /@ {12.34, 1234.56}

Out[1]= {"123.5", "0.001235"}

Out[2]= {"789", "0.8"}

Out[3]= {"0.12", "1234"}

Out[4]= {"12.3", "1235"}

答案 1 :(得分:1)

这可能不是完整的答案(您需要从/转换为字符串),但此函数会将参数设为x,并且需要有效数字sig。它保留的位数是sig的最大值或小数点左边的位数。

A[x_,sig_]:=NumberForm[x, Max[Last[RealDigits[x]], sig]]

RealDigits

答案 2 :(得分:0)

这是我原始功能的可能概括。 (我已经确定它不等同于Wizard先生的解决方案,但我不确定我认为哪个更好。)

re = RegularExpression;

(* Show Number. Convert to string w/ no trailing dot. Use at most d significant
   figures after the decimal point. Target t significant figures total (clipped 
   to be at least i and at most i+d, where i is the number of digits in integer 
   part of x). *)
shn[x_, d_:5, t_:16] := ToString[x]
shn[x_?NumericQ, d_:5, t_:16] := With[{i= IntegerLength@IntegerPart@x},
  StringReplace[ToString@NumberForm[N@x, Clip[t, {i,i+d}],
                                    ExponentFunction->(Null&)],
                re@"\\.$"->""]]

测试:

这里我们指定了4位有效数字,但是从不丢弃小数点左边的任何数字,并且从不在小数点右边使用超过2位有效数字。

(# -> shn[#, 2, 4])& /@ 
  {123456, 1234.4567, 123.456, 12.345, 1.234, 1.0001, 0.123, .0001234}

{  123456 -> "123456", 
 1234.456 -> "1234", 
  123.456 -> "123.5"
   12.345 -> "12.35", 
    1.234 -> "1.23", 
   1.0001 -> "1", 
    0.123 -> "0.12", 
0.0001234 -> "0.00012" }
相关问题