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

Please help explain sprintf

Hello,

Anyone can explain about sprintf?

suppose number = 100.5

and then run this sprintf("$%0.2f", number)

it becomes $100.50

But I don't get how that works even though I've read through the documentation.

Thanks before

1 Answer

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

I'll try to explain it symbol by symbol:

$ - this symbol will precede the resulting number. You can put virtually anything here. If you put ABC instead of $, the resulting string will be "ABC100.50"

% - This is a placeholder where the number will go in the whole formatting - things that precede this symbol will be literally interpreted as things you want to print in front of the number

0.2 - or even simply .2 ("$%.2f") tells the method how many decimal places you want to print, two in this case. 0.1 would give you one - "$100.5", 0.3 would give you three - "$100.500" etc.

f - this is the type you want as a result. "f" stands for floating point number. "i" would give you an integer (no decimal places at all).

number - that's the variable you are passing to the whole sprintf formatting method. You can pass a variable, like Jason did, or an actual number, like this: sprintf("$%0.2f", 100.5)

Do some experiments to see this in action.

Thank you! really helps!!