Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a string with floats in Ruby using #{variable}?

Tags:

ruby

I would like to format a string containing float variables including them with a fixed amount of decimals, and I would like to do it with this kind of formatting syntax:

amount = Math::PI puts "Current amount: #{amount}" 

and I would like to obtain Current amount: 3.14.

I know I can do it with

amount = Math::PI puts "Current amount %.2f" % [amount] 

but I am asking if it is possible to do it in the #{} way.

like image 357
marcotama Avatar asked Sep 12 '12 13:09

marcotama


People also ask

How do I format a string in Ruby?

In Ruby we apply the string format syntax (the "%" operator) to ease this creation of formatted string data. After the "%" we specify arguments. A first example. We use the percentage sign ("%") to specify a format code within a string.

How do you format a float?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you round a float to 2 decimal places in Ruby?

Ruby has a built in function round() which allows us to both change floats to integers, and round floats to decimal places. round() with no argument will round to 0 decimals, which will return an integer type number. Using round(1) will round to one decimal, and round(2) will round to two decimals.

What is #{} in ruby?

The #{} literal is the operator used for interpolation inside double-quoted strings the same way that the backticks or $() construct would be used in Bash.


2 Answers

You can use "#{'%.2f' % var}":

irb(main):048:0> num = 3.1415 => 3.1415 irb(main):049:0> "Pi is: #{'%.2f' % num}" => "Pi is: 3.14" 
like image 144
Spajus Avatar answered Sep 21 '22 06:09

Spajus


Use round:

"Current amount: #{amount.round(2)}" 
like image 23
Bjoernsen Avatar answered Sep 20 '22 06:09

Bjoernsen