3

I want to round a float with many decimal places, such as 2.638232371 down to one decimal place, such as 2.6.

I found this will do so:

"%.2f" % 1.93213
#=> 1.93

But what is "%.2f"? and is the result a string? I'd just like to understand how this works.

GroundBeesAhh
  • 133
  • 1
  • 4
  • 11

2 Answers2

4

It's the format string used by Kernel#sprintf.

The syntax of a format string is:

%[flags][width][.precision]type

%.2f means to use the floating-point format with 2 digits of precision.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

Try this in irb and see for yourself whether or not the result is a String:

result = "%.2f" % 1.93213
result.class

As for what "%.2f" means, check out the sprintf docs

Some Guy
  • 1,481
  • 12
  • 26