# Specifying precision of a number in StringForm[]

I want to use StringForm to provide the headers to a table of numbers I have just calculated. Basically, I want the top row of spots in the table to have the form $D = x~~\text{(nm)}$, where x corresponds to a non-rational number which I had used in the calculations to make the table. While I can directly place the numerical output in the body of the table and use SetPrecision to print an appropriate number of decimal places, this does not work when using StringForm to format the headers of the columns. Try it for yourself:

testd = RandomReal[1, 16] Table[StringForm["n = ", testd[[i]]], {i, Length[testd]}] Table[StringForm["n = ", SetPrecision[testd[[i]], 3]], {i, Length[testd]}]

Where the last line will output the randomly generated numbers to machine precision, while I want the formatted headers to have three decimal places of precision. Is there a way around this strange shortcoming?

EDIT: I should note that I already tried passing in the table after SetPrecision acted on the freshly-generated random numbers, i.e.

test1 = RandomReal[1, 16] test2 = SetPrecision[test1, 3] Table[StringForm["n = ", test2[[i]]], {i, Length[test2]}] Table[StringForm["n = ", SetPrecision[test2[[i]], 3]], {i, Length[test2]}]

Still does not work.

## 1 Answer

SetPrecision is not a formatting tool; it sets the precision of the numbers as used by the precision tracking engine of Mathematica. As such it does not truncate the internal representation. Instead you want a formatting tool like NumberForm:

testd = RandomReal[1, 16]

Table[StringForm["n = ", NumberForm[testd[[i]], {3, 3}]], {i, Length[testd]}]

{n = 0.100, n = 0.203, n = 0.887, n = 0.641, n = 0.836, n = 0.423, n = 0.468,
n = 0.990, n = 0.436, n = 0.035, n = 0.631, n = 0.068, n = 0.763, n = 0.319,
n = 0.006, n = 0.831}

• Exactly what I was looking for. Thank you! Mar 5, 2017 at 3:43