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


Ruby Kernel.BigDecimal用法及代碼示例

本文簡要介紹ruby語言中 Kernel.BigDecimal 的用法。

用法

BigDecimal(value, exception: true) → bigdecimal
BigDecimal(value, ndigits, exception: true) → bigdecimal
Returns the \BigDecimal converted from +value+
with a precision of +ndigits+ decimal digits.

When +ndigits+ is less than the number of significant digits
in the value, the result is rounded to that number of digits,
according to the current rounding mode; see BigDecimal.mode.

返回 value 轉換為 BigDecimal,具體取決於 value 的類型:

  • Integer Float Rational Complex 或 BigDecimal: 直接轉換:

    # Integer, Complex, or BigDecimal value does not require ndigits; ignored if given.
    BigDecimal(2)                     # => 0.2e1
    BigDecimal(Complex(2, 0))         # => 0.2e1
    BigDecimal(BigDecimal(2))         # => 0.2e1
    # Float or Rational value requires ndigits.
    BigDecimal(2.0, 0)                # => 0.2e1
    BigDecimal(Rational(2, 1), 0)     # => 0.2e1
  • 字符串:如果包含整數或浮點字麵量,則通過解析轉換;前導和尾隨空格被忽略:

    # String does not require ndigits; ignored if given.
    BigDecimal('2')     # => 0.2e1
    BigDecimal('2.0')   # => 0.2e1
    BigDecimal('0.2e1') # => 0.2e1
    BigDecimal(' 2.0 ') # => 0.2e1
  • 響應方法 :to_str 的其他類型:首先轉換為字符串,然後轉換為 BigDecimal,如上。

  • 其他類型:

    • 如果關鍵字參數 exceptiontrue 則引發異常。

    • 如果關鍵字參數 exceptiontrue ,則返回 nil

如果 value 計算結果為 Float 並且 digits 大於 Float::DIG + 1,則引發異常。

相關用法


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