1
$\begingroup$

Was looking for something like Matlab's num2str function. I'm trying to use Grid to format output from a print statement, but some of the cells are complex like

"distance result = ", list[[2]], " meters "

The Print function has no problem with that

Print["distance result = ", list[[2]], " meters "]
Print["time result = ", list[[3]], " days "]

but if I try

Grid[{{"distance result = " <> IntegerString[list[[2]]]}," meters "},{"time result = " <> IntegerString[list[[3]]]," days "}},Alignment-> Left]

This only works if list[[2]] and list[[3]] are integers. How do I do this if list contains real numbers, i.e., IntegerString no longer works? I would like meters and days to be vertically aligned. I think I need to intermix text and real numbers inside a single grid cell. Maybe there is a better way to format outputs? Do I put separate Print statements inside each Grid cell? Not sure how to get properly formatted multi-line output in notebooks.

$\endgroup$
1
  • $\begingroup$ ToString should do it $\endgroup$
    – Stitch
    Apr 18, 2017 at 19:18

2 Answers 2

1
$\begingroup$

You need to use ToString:

list = {1.5, 2.5, 3.5};
Grid[{{"distance result = " <> ToString[list[[2]]], " meters "}, 
      {"time result = " <> ToString[list[[3]]], " days "}}, Alignment -> Left]
$\endgroup$
1
  • 2
    $\begingroup$ You might want to look at Alignment -> "=" $\endgroup$
    – Bob Hanlon
    Apr 18, 2017 at 19:25
3
$\begingroup$

I would use Row instead of converting everything to a string and concatenating. Also, you can use the built-in Quantity system as well. So, something like:

list = {1, 2.2, 3.333};
Column[{
    Row[{"distance result = ", Quantity[list[[2]], "Meters"]}],
    Row[{"time result = ", Quantity[list[[3]], "Days"]}]
    },
    Alignment->"="
]

enter image description here

There are several issues when converting to a string. In your case, a problematic example is a number like 1.1*10^-6:

ToString[1.1*10^-6] //InputForm

(* "      -6\n1.1 10" *)
$\endgroup$
1
  • $\begingroup$ This is nice too. Quantity looks like a neat command. The example I gave was a bit simplified as my list vector might not be the only item I want to put in a cell. There might be more text and more numbers all needing to go into one cell. But thanks for steering me to Quantity and Row. I do like how Row helps visually organize the cells. $\endgroup$ Apr 18, 2017 at 20:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.