user6925364
user6925364

Reputation:

Sprintf flags and width - Ruby

I am trying to understand how sprintf works.

Looking at the documentation here's the format/syntax %[flags][width][.precision]type

I tried to understand my code here:

format('%02.2f', monthly_payment)

focusing on %02.2f I understand that .2f means round it to two decimal float but what does %02 means?

Breaking it down like this:

Can anyone explain this in a layman's term and give examples (to better understand this concept) that I can try out on irb?

Upvotes: 1

Views: 1043

Answers (1)

max pleaner
max pleaner

Reputation: 26778

%02.2f

has these parts:

  • 02 is split into two parts:
    • 0 is the flag
    • 2 is the minimum width
  • .2: precision (amount of zeros)
  • f: type (float)

The difference between %2.0 and %02.0 is the flag. If it's given, then the minimum width will be enforced by left-padding zeros. Otherwise, whitespace will be left-padded.

You can right-pad instead by using a -.

Note that the minimum-width will include the decimal space if there is one.

To give some example with the string '1':

format('%2f', "1")
=> "1.000000"
# Here I'm only specifying that the length is 'at least 2'.

format('%2.0f', "1")
=> " 1"
# min-width of 2, precision of zero, and padding with whitespace

format('%.2f', "1")
=> "1.00"
# just set precision, don't set min-width

format('%02.0f', "1")
=> "01"
# min-width of 2, precision of zero, and padding with zeroes

format('%-2.0f', "1")
=> "1 "
# using a dash to right pad

format('%-02.0f', "1")
=> "1 "
# when '-' is used the 0 flag will still pad with whitespace

format('%2.2f', "1")
=> "1.00"
# min-width of 2 and precision of 2

format('%5.2f', "1")
=> "01.00"
# min-width of 5, precision of 2, padding with whitespace

Upvotes: 1

Related Questions