Welcome to the Treehouse Community
Looking to learn something new?
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?
Christine Merey3,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