String Formatting
In this page:
String Formatting
The % operator (or the format/sprintf methods) formats values into a string using format specifiers like %s, %d, and %.2f, similar to C's printf. This gives more precise control over output than plain interpolation, such as fixed decimal places or zero-padding. format and sprintf are aliases for the same underlying behavior.
Note: format("%.2f", value) is the standard way to format a number to exactly 2 decimal places.
Example: String Formatting
name = "Alice"
score = 92.567
puts format("Name: %s, Score: %.2f", name, score)
puts "Padded: %05d" % 42
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: