반응형
루비에서 반올림 플로트
반올림에 문제가 있습니다. 부동 소수점이 있습니다. 소수점을 100으로 반올림하고 싶습니다. 그러나 .round
기본적으로 int로 변환하는 것을 사용할 수 있습니다 . 즉, 2.34.round # => 2.
다음과 같은 간단한 효과 방법이 있습니까?2.3465 # => 2.35
표시 할 때 (예를 들어)
>> '%.2f' % 2.3465
=> "2.35"
둥근 모양으로 저장하려면
>> (2.3465*100).round / 100.0
=> 2.35
반올림 할 소수점 이하 자릿수를 포함하는 반올림에 인수를 전달하십시오.
>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347
Float Class에 메소드를 추가 할 수 있습니다.
class Float
def precision(p)
# Make sure the precision level is actually an integer and > 0
raise ArgumentError, "#{p} is an invalid precision level. Valid ranges are integers > 0." unless p.class == Fixnum or p < 0
# Special case for 0 precision so it returns a Fixnum and thus doesn't have a trailing .0
return self.round if p == 0
# Standard case
return (self * 10**p).round.to_f / 10**p
end
end
이것을 precison으로 반올림하는 데 사용할 수 있습니다 ..
//to_f is for float
salary= 2921.9121
puts salary.to_f.round(2) // to 2 decimal place
puts salary.to_f.round() // to 3 decimal place
또한 round
10, 100 등의 가장 가까운 배수로 반올림 하는 메소드 의 인수로 음수를 제공 할 수도 있습니다 .
# Round to the nearest multiple of 10.
12.3453.round(-1) # Output: 10
# Round to the nearest multiple of 100.
124.3453.round(-2) # Output: 100
def rounding(float,precision)
return ((float * 10**precision).round.to_f) / (10**precision)
end
무엇에 대해 (2.3465*100).round()/100.0
?
그냥 표시 해야하는 경우 number_with_precision 도우미를 사용합니다 . 당신이 다른 곳이 필요하면 스티브 Weet가 지적했듯이 나는, 사용하는 것입니다 round
방법을
루비 1.8.7의 경우 코드에 다음을 추가 할 수 있습니다.
class Float
alias oldround:round
def round(precision = nil)
if precision.nil?
return self
else
return ((self * 10**precision).oldround.to_f) / (10**precision)
end
end
end
참고 URL : https://stackoverflow.com/questions/2054217/rounding-float-in-ruby
반응형
'Programing' 카테고리의 다른 글
안드로이드의 액션 바에서 아이콘 / 로고 제거 (0) | 2020.06.15 |
---|---|
“오류 TS2533 : 개체가 'null'또는 'undefined'일 수 있습니다.”를 억제하는 방법은 무엇입니까? (0) | 2020.06.15 |
node.js : 텍스트 파일을 배열로 읽습니다. (0) | 2020.06.15 |
iOS 앱 최대 메모리 예산 (0) | 2020.06.15 |
gmtime ()의 시간 + 날짜 출력에서 신기원 이후 초를 얻는 방법은 무엇입니까? (0) | 2020.06.15 |