Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Foundations Numbers Random Numbers and Formatting

Formatting numbers in Ruby

I don’t understand how we got from sprint(“$%0.2f”, number) to “$100.50$ in this video.

I know this is the sprintf syntax, as given by the kernel module docs: %[flags][width][.precision]type.

So type = f and precision = 2 (because we want 2 digits after the decimal) Why is width 0? Also why did Jason put the % after the $ in the video? Isn't it the other way around?

1 Answer

The field width specifies the minimum size of the field. In this case the 0 is unnecessary, but it may improve readability. Try omitting it, and you get the same result:

sprintf("$%.2f", number) # => "$100.50"

It's clearer if you make the field width 20 (it's not very clear in Markdown, but it is in irb):

sprintf("$%20.2f", number) # => "$ 100.50"

He inserts the $ before % because he wants $ to appear before number. We could insert & instead:

sprintf("&%0.2f", number) # => "&100.50"; or even "foo bar ":

sprintf("foo bar %0.2f", number) # => "foo bar 100.50"

If you place $ after % it has a special meaning and you get an error:

sprintf("%$0.2f", number) # => ': malformed format string - %$ (ArgumentError)

Everything between % and type has special meaning (but is optional):
%[flags][width][.precision]type - Let's move the $ to be after number:

sprintf("%0.2f$", number) # => "100.50$"

Now format two strings, left-justify one, then right-justify the other (again, not 28 wide in Markdown):

sprintf("%-10s center %10s", "Left", "Right") # "Left center Right"

Definitely play around with it.

There are lots of examples here: http://apidock.com/ruby/Kernel/sprintf and you can also read another Forum post here: https://teamtreehouse.com/forum/please-help-explain-sprintf