Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppressing a trailing "." in numerical output from Mathematica

Is there some straightforward way to ensure that, when converted to strings, approximate numbers (i.e., numbers with the Real head) won't have a trailing "."? I would like it if they were to only have the decimal point in cases where there's actually a displayed fractional part.

The solutions I've found are not robust, and depend on using Precision and Accuracy together NumberForm in an awkward way, or using RealDigits in an even more awkward way.

Thanks in advance.

like image 997
Pillsy Avatar asked Oct 09 '09 20:10

Pillsy


2 Answers

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.

like image 184
Will Robertson Avatar answered Sep 22 '22 07:09

Will Robertson


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@"\\.$"->""]
like image 39
dreeves Avatar answered Sep 23 '22 07:09

dreeves