반응형
# {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)}"
반응형
'programing' 카테고리의 다른 글
Javascript에서 Regex 캡처 그룹을 대문자로 바꾸기 (0) | 2020.11.10 |
---|---|
첫 번째 명령 후 배치 파일 실행이 중지됨 (0) | 2020.11.10 |
반환 값을 둘러싼 괄호 (0) | 2020.11.10 |
PNG 이미지를 생성 / 편집하는 무료 도구? (0) | 2020.11.10 |
UITableViewCell에서 부모 UITableView 로의 참조? (0) | 2020.11.10 |