Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do number to string suffix

As you know in ruby you can do

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

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

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

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

just wondering is there possibility to do number string suffix in similar nice way ? (please no if statements)

something 5
#=> 500

something 55
#=> 550

something 555
# => 555
like image 464
equivalent8 Avatar asked Jul 16 '12 10:07

equivalent8


1 Answers

how about ljust method?

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

and some to_s and to_i method calls if you want to do that to integers

you could avoid string conversion with bit more math like log_10 to find number of digits in an integer and then i *= 10**x where x is how many more 0's you need

like this:

def something(int, power=3)
  int * 10**([power - Math.log10(int).to_i - 1, 0].max)
end
like image 173
keymone Avatar answered Nov 01 '22 10:11

keymone