# How to set number of digits automatically in NumberForm?

I have a code where I used NumberForm[i] where i can be an integer or rational number. I would like the output to have the same digits as in i. minimal example:

Table[NumberForm[i], {i, 0., 0.05, 0.01}]
{0.,0.01,0.02,0.03,0.04,0.05}


The first element shows only one digit 0. I want it to be 0.00 same digits as the rest. I know that for this case it can be done like this

Table[NumberForm[i, {2, 2}], {i, 0., 0.05, 0.01}]
{0.00,0.01,0.02,0.03,0.04,0.05}


but then I need to change the second element of {2,2} every time the digits of i change, e.g.

    Table[NumberForm[i, {2, 1}], {i, 0, 0.5, 0.1}]
{0.0,0.1,0.2,0.3,0.4,0.5}


How can I automatically make the digits in the output the same as the step size of i?

• Your example with Table makes this impractical, and I think it is perhaps not representative of your actual usage. The only way you could do this is if the formatting function had access to ALL your numbers at once, so it can determine how many digits are needed overall, and apply them uniformly. In comments below you also mentioned that your numbers come from a dataset and are not generated programmatically, so please update the question with an example more closely resembling your application. Jun 22 at 14:42

NumberForm[tab = Table[i, {i, 0., 0.005, 0.001}],
{2, -Min[RealDigits[DeleteCases[tab, 0.0]][[All, -1]]] + 1}]


{0.000, 0.001, 0.002, 0.003, 0.004, 0.005}

• that is exactly what I need but what if i runs from 0 to 50 or 500?...NumberForm[tab = Table[i, {i, 0., 50, 10}], {2, -Min[RealDigits[DeleteCases[tab, 0.0]][[All, -1]]] + 1}] Jun 22 at 15:55
• How about this? NumberForm[tab = Table[i, {i, 0., 500.005, 10.001}], {Max[0, Floor[Log10[DeleteCases[tab, 0.0]]]] + 1 + (f = -Min[ RealDigits[DeleteCases[FractionalPart[tab], 0.0]][[All, -1]]]), f}] Jun 22 at 16:18
• Could probably be simplified. Jun 22 at 16:23

You could parameterize the whole expression:

With[
{digits = 3},
Table[NumberForm[N[i], {digits, digits}], {i, 0, 5 10^-digits, 10^-digits}]]

• that is not practical because i is imported from a data set, I can't write it in the form you did Jun 22 at 14:27
• Well then, show us what your input actually is Jun 22 at 14:39
• @valarmorghulis The OP doesn't mention anything about data. The examples just show instances of Table with a problem only at i = 0. Maybe this is a better MWE: max = RandomInteger[{1, 4}]; data = Union[{0.}, Round[RandomReal[1, 10], 10.^-RandomInteger[{1, max}, 10]]]; Table[NumberForm[ ...], {i, data}], where max is unknown but could be inferred from data. Jun 22 at 14:41