本文簡要介紹ruby語言中 Float.round
的用法。
用法
round(ndigits = 0, half: :up]) → integer or float
返回 self
四舍五入到最接近的值,精度為 ndigits
十進製數字。
當ndigits
為非負數時,返回小數點後帶有ndigits
的浮點數(如可用):
f = 12345.6789
f.round(1) # => 12345.7
f.round(3) # => 12345.679
f = -12345.6789
f.round(1) # => -12345.7
f.round(3) # => -12345.679
當ndigits
為負數時,返回一個至少帶有ndigits.abs
尾隨零的整數:
f = 12345.6789
f.round(0) # => 12346
f.round(-3) # => 12000
f = -12345.6789
f.round(0) # => -12346
f.round(-3) # => -12000
如果給出關鍵字參數half
,並且self
與兩個候選值等距,則根據給定的half
值進行舍入:
-
:up
或nil
:從零四舍五入:2.5.round(half: :up) # => 3 3.5.round(half: :up) # => 4 (-2.5).round(half: :up) # => -3
-
:down
:向零舍入:2.5.round(half: :down) # => 2 3.5.round(half: :down) # => 3 (-2.5).round(half: :down) # => -2
-
:even
:向最後一個非零數字為偶數的候選者四舍五入:2.5.round(half: :even) # => 2 3.5.round(half: :even) # => 4 (-2.5).round(half: :even) # => -2
如果 half
的值無效,則引發和異常。
相關: Float#truncate
。
相關用法
- Ruby Float.rationalize用法及代碼示例
- Ruby Float.self - other用法及代碼示例
- Ruby Float.truncate用法及代碼示例
- Ruby Float.quo用法及代碼示例
- Ruby Float.finite?用法及代碼示例
- Ruby Float.self / other用法及代碼示例
- Ruby Float.coerce用法及代碼示例
- Ruby Float.self < other用法及代碼示例
- Ruby Float.numerator用法及代碼示例
- Ruby Float.nan?用法及代碼示例
- Ruby Float.to_int用法及代碼示例
- Ruby Float.self % other用法及代碼示例
- Ruby Float.self >用法及代碼示例
- Ruby Float.fdiv用法及代碼示例
- Ruby Float.next_float用法及代碼示例
- Ruby Float.eql?用法及代碼示例
- Ruby Float.to_d用法及代碼示例
- Ruby Float.to_i用法及代碼示例
- Ruby Float.self + other用法及代碼示例
- Ruby Float.self >=用法及代碼示例
- Ruby Float.self ** other用法及代碼示例
- Ruby Float.modulo用法及代碼示例
- Ruby Float.self ==用法及代碼示例
- Ruby Float.self * other用法及代碼示例
- Ruby Float.abs用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Float.round。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。