programing

# {variable}을 사용하여 Ruby에서 float로 문자열을 포맷하는 방법은 무엇입니까?

nasanasas 2020. 11. 10. 08:16
반응형

# {variable}을 사용하여 Ruby에서 float로 문자열을 포맷하는 방법은 무엇입니까?


고정 된 양의 소수를 포함하는 부동 변수를 포함하는 문자열의 형식을 지정하고 싶습니다. 이러한 형식의 구문을 사용하고 싶습니다.

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

을 얻고 싶습니다 Current amount: 3.14.

나는 그것을 할 수 있다는 것을 안다.

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

하지만 그렇게 할 수 있는지 묻고 #{}있습니다.


사용 round:

"Current amount: #{amount.round(2)}"

다음을 사용할 수 있습니다 "#{'%.2f' % var}".

irb(main):048:0> num = 3.1415
=> 3.1415
irb(main):049:0> "Pi is: #{'%.2f' % num}"
=> "Pi is: 3.14"

이 작업을 수행 할 수 있지만 다음 String#%버전을 선호합니다 .

 puts "Current amount: #{format("%.2f", amount)}"

@Bjoernsen이 지적했듯이 round는 가장 간단한 접근 방식이며 Rails뿐만 아니라 표준 Ruby (1.9)에서도 작동합니다.

http://www.ruby-doc.org/core-1.9.3/Float.html#method-i-round


예, 가능합니다 :

puts "Current amount: #{sprintf('%.2f', amount)}"

참고 URL : https://stackoverflow.com/questions/12389567/how-to-format-a-string-with-floats-in-ruby-using-variable

반응형