When I need to print numbers without knowing how large or small they may
become, in a fixed width of n characters and an accuracy of (at least) m
figures, I mostly use the “%n.mg” format. For example:
-10.upto(10) do |i| puts “%12.6g” % [1.234234234*10**i] end
would print the first column below.
However, my spreadsheet (LibreOffice) does a better job; it would print
the second column below, keeping more significant figures and using less
scientific formats.
Finally, I would appreciate the third column even better, as it keeps
the maximum number of significant figures within the available width.
Is there an elegant way to do this in Ruby?
1.23423e-10 1.2342e-010 1.23423e-10
1.23423e-09 1.2342e-009 1.234234e-9
1.23423e-08 1.2342e-008 1.234234e-8
1.23423e-07 1.2342e-007 1.234234e-7
1.23423e-06 1.2342e-006 1.234234e-6
1.23423e-05 1.2342e-005 1.234234e-5
0.000123423 0.000123423 0.000123423
0.00123423 0.001234234 0.001234234
0.0123423 0.01234234 0.01234234
0.123423 0.1234234 0.1234234
1.23423 1.234234 1.234234
12.3423 12.34234 12.34234
123.423 123.4234 123.4234
1234.23 1234.234 1234.234
12342.3 12342.34 12342.34
123423 123423.4 123423.4
1.23423e+06 1234234 1234234
1.23423e+07 12342342 12342342
1.23423e+08 123423423 123423423
1.23423e+09 1234234234 1234234234
1.23423e+10 12342342340 12342342340