dre*_*ves 3 utilities wolfram-mathematica
我使用以下函数将数字转换为字符串以供显示(不要使用科学记数法,不要使用尾随点,指定圆形):
(* 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@"\\.$"->""]
Run Code Online (Sandbox Code Playgroud)
(注意,它re是.的别名RegularExpression.)
多年来我一直很好.但有时我不想指定要舍入的位数,而是我想指定一些有效数字.例如,123.456应显示为123.5,但0.00123456应显示为0.001235.
为了得到真正的幻想,我可能想要在小数点之前和之后指定有效数字.例如,我可能希望.789显示为0.8但是789.0显示为789而不是800.
对于这类事情,你有一个方便的实用功能,还是上面概括我的功能的建议?
更新:我试着在这里询问这个问题的一般版本:https:
//stackoverflow.com/questions/5627185/displaying-numbers-to-non-technical-users
dreeves,我想我终于理解了你想要的东西,而且你已经拥有了它,非常多.如果没有,请再次尝试解释我所缺少的内容.
shn2[x_, r_: 0] :=
StringReplace[
ToString@NumberForm[x, r, ExponentFunction -> (Null &)],
RegularExpression@"\\.0*$" -> ""]
Run Code Online (Sandbox Code Playgroud)
测试:
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"}
Run Code Online (Sandbox Code Playgroud)