Suppressing a trailing “.” in numerical output from Mathematica

故事扮演 提交于 2019-12-05 05:39:34

I've used this in the past when displaying numbers in figures:

Integerise[x_] := If[Round[x] == x, ToString[Round@x] <> ".0", ToString@x]

Just remove <> ".0" if you don't want integers to be displayed with a zero decimal.

Update: As mentioned by dreeves in the comment, ToString will still truncate a number within 0.0001 or so of an integer and display the dot.

A better way to remove the trailing dot is to use the Inputform format for ToString:

NormalNumber[x_] := ToString[x, InputForm]

with a test:

NormalNumber /@ {5, 5.5, 123.001, 123.0001}

This could be incorporated into Integerise above to fix the problem noted.

I recommend this:

shownum[x_] := StringReplace[ToString@NumberForm[x, ExponentFunction->(Null&)], 
                             RegularExpression["\\.$"]->""]

It just does a regex search&replace on the trailing ".". If you want "123." to display as "123.0" instead of "123" then just replace that final empty string with ".0".

UPDATE: My original version displayed wrong for numbers that Mathematica by default displays in scientific notation. I fixed that with NumberForm.

Here's the version I actually use in real life. It allows for optional rounding:

(* Show Number. Convert to string w/ no trailing dot. Round to the nearest r. *)
Unprotect[Round];   Round[x_,0] := x;   Protect[Round];
re = RegularExpression;
shn[x_, r_:0] := StringReplace[
  ToString@NumberForm[Round[N@x,r], ExponentFunction->(Null&)], re@"\\.$"->""]

I'd probably just post-process the string. It's faster (and way easier) to just check if the last character is "." than to do redundant arithmetic and take into account all the precision settings.

Edit: maybe you know this, but you can do something like this:

userToString[expr_, form___] := ToString[expr,form];

userToString[expr_Real, form___] := removeTrailingDot[ToString[expr,form]];

The functions NumberForm, ScientificForm, EngineeringForm, etc. ... offers the option NumberFormat to format and arrange the mantissa, base and exponent of a number. With

numberTrim[expr_] := NumberForm[expr,
   NumberFormat -> (Row[{StringTrim[#1, "."], 
        If[#3 == "", "", "\[ThinSpace]\[Times]\[ThinSpace]" <> #2^#3]}] &)];

the default Mathematica output is reproduced, but the trailing dot is removed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!