I can use "%.5f" % var_name to format a float var_name where 5 represents a fixed number of decimal places. How can I dynamically change this number? I tried "%.%f" % var_name, 5 and "#{var_name}.#{5}f", but they didn't work.

有帮助吗?

解决方案

You should try:

"%.#{5}f" % var_name

with variables:

var_name = 0.00001
num = 5

"%.#{num}f" % var_name
# => "0.00001"

num = 6
"%.#{num}f" % var_name
# => "0.000010"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top