Arjen Markus 2003-02-11: I had a question from a customer about numbers that were displayed with too many digits, like 28.000 instead of 28.0. So, this raised the question: what can we do to make the appearance of (floating-point) numbers more elegant?
As it turns out, format has a lot of options, one of them is the # attribute to %g. Now, if all you have is the textual description of the effects, you will be very puzzled indeed.
So, here is a little script that examines the effects:
# Check the effects of the various formats for floating-point numbers # foreach value {1.0 -1.0 1.01 -1.01 0.00001 -0.00001 1000000.0 -1000000.0} { set result {} foreach form {%g %-g %6g %6.4g %#.4g %06g %-6g} { append result [format " >$form<" $value] } puts "Value $value: $result" }
I have reformatted the output a bit, to get the following table:
Formats: | %g | %-g | %6g | %6.4g | %#.4g | %06g | %-6g |
---|---|---|---|---|---|---|---|
Value 1.0: | >1< | >1< | > 1< | > 1< | >1.000< | >000001< | >1 < |
Value -1.0: | >-1< | >-1< | > -1< | > -1< | >-1.000< | >-00001< | >-1 < |
Value 1.01: | >1.01< | >1.01< | > 1.01< | > 1.01< | >1.010< | >001.01< | >1.01 < |
Value -1.01: | >-1.01< | >-1.01< | > -1.01< | > -1.01< | >-1.010< | >-01.01< | >-1.01 < |
Value 0.00001: | >1e-05< | >1e-05< | > 1e-05< | > 1e-05< | >1.000e-05< | >01e-05< | >1e-05 < |
Value -0.00001: | >-1e-05< | >-1e-05< | >-1e-05< | >-1e-05< | >-1.000e-05< | >-1e-05< | >-1e-05< |
Value 1000000.0: | >1e+06< | >1e+06< | > 1e+06< | > 1e+06< | >1.000e+06< | >01e+06< | >1e-06 < |
Value -1000000.0: | >-1e+06< | >-1e+06< | >-1e+06< | >-1e+06< | >-1.000e+06< | >-1e+06< | >-1e+06< |
However, there's more! The full format specification is huge and very, very complex. Here it is, bit by bit, aimed at people doing float formatting...
(AM That complexity is precisely the reason to have this page - so you can see the effects :))
So, if we want a left formatted normal float in a gap at least 8 characters wide and to not have the start of the number jump around when going between positive and negative numbers while taking the number of values after the decimal point from a variable, you should use the format "%- 8.*f" (and yes, the space is significant.)
In the Tcl Chatroom, 2014-07-17, AM pointed out that the following operation can be used to set the string value of a floating point number to a precision of 2 without losing its internal numeric representation:
expr {int(100*$x+0.5)/100.0}
An equivalent operation using round:
expr {round(100*$x)/100.0}
Generalized and implemented as an extension to expr:
proc ::tcl::mathfunc::precision {precision float} { expr {round( 10 ** $precision * $float) / (10.0 ** $precision)} }