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.
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.
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 %.
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.
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.
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"
Use round
:
"Current amount: #{amount.round(2)}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With