Although there is an internal difference between 0
and 0.
, that doesn't mean that you have to display the floating point zero as 0.
every time. You also may not always want to use Rationalize
because in a matrix it can create an unbalanced, "non-uniform" appearance.
Instead, you can customize the format in which floating point numbers are displayed by using a definition like this:
trimPoint =
Sequence[NumberFormat -> (DisplayForm@
RowBox[Join[{StringTrim[#1, RegularExpression["\\.$"]]},
If[#3 != "", {"\[Times]", SuperscriptBox[#2, #3]}, {}]]] &)]
This is meant to be used as an optional argument to the formatting functions NumberForm
, ScientificForm
, EngineeringForm
and AccountingForm
.
I posted something like this as part of another answer but not in a way that's easily used on matrices.
Example
Define a random matrix m
with one floating-point zero element:
m = RandomReal[{0, 1}, {5, 5}]; m[[1, 1]] = 0.;
m // MatrixForm
$ \left(
\begin{array}{ccccc}
0. & 0.0712901 & 0.00252376 & 0.930725 & 0.0120859
\\
0.504716 & 0.537549 & 0.715322 & 0.351001 &
0.363718 \\
0.905092 & 0.0874893 & 0.624776 & 0.546527 &
0.542502 \\
0.0776307 & 0.360377 & 0.388662 & 0.406045 &
0.441652 \\
0.947527 & 0.270716 & 0.0121501 & 0.744597 &
0.830463 \\
\end{array}
\right)
$
Here we have the 0.
appearing in the top left entry, but maybe that's not desired. To remove the decimal point where it isn't followed by any nonzero digits, you can now do this:
NumberForm[m // MatrixForm, trimPoint]
$ \left(
\begin{array}{ccccc}
0 & 0.0712901 & 0.00252376 & 0.930725 & 0.0120859
\\
0.504716 & 0.537549 & 0.715322 & 0.351001 &
0.363718 \\
0.905092 & 0.0874893 & 0.624776 & 0.546527 &
0.542502 \\
0.0776307 & 0.360377 & 0.388662 & 0.406045 &
0.441652 \\
0.947527 & 0.270716 & 0.0121501 & 0.744597 &
0.830463 \\
\end{array}
\right)
$
Notice that the decimal point following the zero is gone, but only in the displayed form (it's still a floating point number internally).
The trimPoint
option can also be used with the other output formats:
EngineeringForm[m // MatrixForm, trimPoint]
etc.
Of course you can also use a second argument to these function to restrict the total number of digits. For example, try
NumberForm[m // MatrixForm, 3, trimPoint]
Finally, if you have numbers like -9.71445146547012*^-17
and want to use Chop
to get rid of them, you can combine that with the above display format by doing something like
NumberForm[m // Chop // MatrixForm, 3, trimPoint]
0.===0
isFalse
. So they approach the same problem from different directions. $\endgroup$