Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Christine Merey
Christine Merey
3,309 Points

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