Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

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.

Returns value converted to a BigDecimal, depending on the type of value:

  • Integer, Float, Rational, Complex, or BigDecimal: converted directly:

    Example
    # 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: converted by parsing if it contains an integer or floating-point literal; leading and trailing whitespace is ignored:

    Example
    # 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
    
  • Other type that responds to method :to_str: first converted to a string, then converted to a BigDecimal, as above.

  • Other type:

    • Raises an exception if keyword argument exception is true.

    • Returns nil if keyword argument exception is true.

Raises an exception if value evaluates to a Float and digits is larger than Float::DIG + 1.