I encountered some syntax during my studies that I do not understand.
puts "He is %d (%3.2f in floating point terms) pounds heavy." % [weight, weight]
The one thing I am not understanding about this is the purpose of 3.2.
Thanks for taking a look!
P.S. By the way the weight variable was originally defined in pounds.
The %n.mf format means the entire output field width is n character positions, and the number of places shown after the decimal point is m, with blank padding in front of the number if necessary to complete the entire field with of n. The decimal is padded right with 0s if needed to bring the number of visible decimal places up to m.
So the value 23.12 with a format of %8.3f will show as bb23.120 (where each b is a blank, not really a b). A format of %8.1f would yield bbbb23.1. A format of %8.0f would give bbbbbb23.
Note that if the formatted number would be more characters than the requested entire field width, then the field will just be made bigger to accommodate the number, so it's not truncated. In the above example, a format of %3.2f for 23.12 would give 23.12.
For the %3.2f case, the field width is given as 3 with 2 digits after the decimal point. Since 2 decimal places plus the decimal point already consume 3 character positions, any float printed with this format will be printed in their entirety with no preceding blanks. You'd get the same result with %2.2f or %1.2f or %0.2f. However this format will always give 2 decimal places either truncating or zero-padding if needed to make it exactly 2 visible digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With