本文簡要介紹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,如上。 -
其他類型:
-
如果關鍵字參數
exception
是true
則引發異常。 -
如果關鍵字參數
exception
是true
,則返回nil
。
-
如果 value
計算結果為 Float
並且 digits
大於 Float::DIG + 1,則引發異常。
相關用法
- Ruby Kernel.local_variables用法及代碼示例
- Ruby Kernel.Integer用法及代碼示例
- Ruby Kernel.binding用法及代碼示例
- Ruby Kernel.frozen?用法及代碼示例
- Ruby Kernel.`cmd`用法及代碼示例
- Ruby Kernel.autoload用法及代碼示例
- Ruby Kernel.loop用法及代碼示例
- Ruby Kernel.Hash用法及代碼示例
- Ruby Kernel.caller用法及代碼示例
- Ruby Kernel.set_trace_func用法及代碼示例
- Ruby Kernel.exit!用法及代碼示例
- Ruby Kernel.trap用法及代碼示例
- Ruby Kernel.String用法及代碼示例
- Ruby Kernel.select用法及代碼示例
- Ruby Kernel.syscall用法及代碼示例
- Ruby Kernel.then用法及代碼示例
- Ruby Kernel.sprintf用法及代碼示例
- Ruby Kernel.Pathname用法及代碼示例
- Ruby Kernel.srand用法及代碼示例
- Ruby Kernel.yield_self用法及代碼示例
- Ruby Kernel.raise用法及代碼示例
- Ruby Kernel.test用法及代碼示例
- Ruby Kernel.pretty_inspect用法及代碼示例
- Ruby Kernel.format用法及代碼示例
- Ruby Kernel.open用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Kernel.BigDecimal。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。