0

I'm trying to figure out how I can format a number, like 29.9, as 29.90. I've tried this so far:

number = 29.90
#=> 29.9

number.to_s
#=> "29.9"

number.round(2).to_s
#=> "29.9"

What method should I use to get "29.90"?

Stefan
  • 109,145
  • 14
  • 143
  • 218
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • Not duplicate because I don't want to set the precision. I want to fill with 0. – Bastien Vandamme Jun 16 '16 at 06:56
  • 2
    '%.02f' % p.round(2) – Gourav Jun 16 '16 at 06:59
  • you are Welcome @B413 – Gourav Jun 16 '16 at 07:06
  • Hey, I've done my best to fix up the English in this question. Look it over and see if I messed anything up. (I assumed you meant just formatting it as a string, rather than printing it, because of your code example) – Nic Jun 16 '16 at 07:27
  • @B413 in case you're wondering why I've renamed the variable: [`p`](http://ruby-doc.org/core-2.3.1/Kernel.html#method-i-p) is a method in Ruby that prints its arguments. And since you're question is related to formatting / output, a variable with the same name can be quite confusing. – Stefan Jun 16 '16 at 07:32

2 Answers2

1
'%.02f' % number
#=> "29.90"

Thanks to Gourav Naik

Stefan
  • 109,145
  • 14
  • 143
  • 218
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
0

Is this working for you?

printf( "%.02f", 22.9 )
devanand
  • 5,116
  • 2
  • 20
  • 19