當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby Rational.round用法及代碼示例

本文簡要介紹ruby語言中 Rational.round 的用法。

用法

round([ndigits] [, half: mode]) → integer or rational

返回 rat 四舍五入到最接近的值,精度為 ndigits 十進製數字(默認值:0)。

當精度為負時,返回值是一個至少有 ndigits.abs 尾隨零的整數。

ndigits 為正數時返回一個有理數,否則返回一個整數。

Rational(3).round      #=> 3
Rational(2, 3).round   #=> 1
Rational(-3, 2).round  #=> -2

  #    decimal      -  1  2  3 . 4  5  6
  #                   ^  ^  ^  ^   ^  ^
  #   precision      -3 -2 -1  0  +1 +2

Rational('-123.456').round(+1).to_f  #=> -123.5
Rational('-123.456').round(-1)       #=> -120

可選的 half 關鍵字參數與 Float#round 類似。

Rational(25, 100).round(1, half: :up)    #=> (3/10)
Rational(25, 100).round(1, half: :down)  #=> (1/5)
Rational(25, 100).round(1, half: :even)  #=> (1/5)
Rational(35, 100).round(1, half: :up)    #=> (2/5)
Rational(35, 100).round(1, half: :down)  #=> (3/10)
Rational(35, 100).round(1, half: :even)  #=> (2/5)
Rational(-25, 100).round(1, half: :up)   #=> (-3/10)
Rational(-25, 100).round(1, half: :down) #=> (-1/5)
Rational(-25, 100).round(1, half: :even) #=> (-1/5)

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Rational.round。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。