Section 5.6. Formatting Numbers with Commas


5.5. Formatting Numbers for Output

To output numbers in a specific format, you can use the printf method in the Kernel module. It is virtually identical to its C counterpart. For more information, see the documentation for the printf method.

x = 345.6789 i = 123 printf("x = %6.2f\n", x)    # x = 345.68 printf("x = %9.2e\n", x)    # x = 3.457e+02 printf("i = %5d\n", i)      # i =   123 printf("i = %05d\n", i)     # i = 00123 printf("i = %-5d\n", i)     # i = 123


To store a result in a string rather than printing it immediately, sprintf can be used in much the same way. The following method returns a string:

str = sprintf("%5.1f",x)    # "345.7"


Finally, the String class has a % method that performs this same task. The % method has a format string as a receiver; it takes a single argument (or an array of values) and returns a string.

# Usage is 'format % value' str = "%5.1f" % x            # "345.7" str = "%6.2f, %05d" % [x,i]  # "345.68, 00123"





The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net