"005" "%03d" % 55 #=> "055" "%03d" % 555 #=> "555"...">

How to make a number in a string suffix

As you know, in ruby ​​you can do

"%03d" % 5
#=>  "005"

"%03d" % 55
#=> "055"

"%03d" % 555
#=> "555"

so basically the number will have the prefix "0" for 3 string places

just wondering if it's possible to make a suffix with a numeric string in a similar glorious way? (please not if statements)

something 5
#=> 500

something 55
#=> 550

something 555
# => 555
+5
source share
2 answers

how about ljust method?

"5".ljust(3, "0")

and some methods to_sand to_iif you want to do this with integers

you can avoid converting strings with bits more than math, for example log_10, to find the number of digits in integer size, and then i *= 10**x, where x- how many more 0 do you need

like this:

def something(int, power=3)
  int * 10**([power - Math.log10(int).to_i - 1, 0].max)
end
+7
source

What about

  def prettify(n)
    ("%03d" % (n.to_s.reverse.to_i)).to_s.reverse
  end

which are

  • converts your number to a string
  • int

, : -)

0

All Articles