Method: Lotus::Utils::Kernel.BigDecimal

Defined in:
lib/lotus/utils/kernel.rb

.BigDecimal(arg) ⇒ BigDecimal

Coerces the argument to be a BigDecimal.

Examples:

Basic Usage

require 'lotus/utils/kernel'

Lotus::Utils::Kernel.BigDecimal(1)                        # => 1
Lotus::Utils::Kernel.BigDecimal(1.2)                      # => 1
Lotus::Utils::Kernel.BigDecimal(011)                      # => 9
Lotus::Utils::Kernel.BigDecimal(0xf5)                     # => 245
Lotus::Utils::Kernel.BigDecimal("1")                      # => 1
Lotus::Utils::Kernel.BigDecimal(Rational(0.3))            # => 0.3
Lotus::Utils::Kernel.BigDecimal(Complex(0.3))             # => 0.3
Lotus::Utils::Kernel.BigDecimal(BigDecimal.new(12.00001)) # => 12.00001
Lotus::Utils::Kernel.BigDecimal(176605528590345446089)
  # => 176605528590345446089

BigDecimal Interface

require 'lotus/utils/kernel'

UltimateAnswer = Struct.new(:question) do
  def to_d
    BigDecimal.new(42)
  end
end

answer = UltimateAnswer.new('The Ultimate Question of Life')
Lotus::Utils::Kernel.BigDecimal(answer)
  # => #<BigDecimal:7fabfd148588,'0.42E2',9(27)>

Unchecked exceptions

require 'lotus/utils/kernel'

# When nil
input = nil
Lotus::Utils::Kernel.BigDecimal(nil) # => TypeError

# When true
input = true
Lotus::Utils::Kernel.BigDecimal(input) # => TypeError

# When false
input = false
Lotus::Utils::Kernel.BigDecimal(input) # => TypeError

# When Date
input = Date.today
Lotus::Utils::Kernel.BigDecimal(input) # => TypeError

# When DateTime
input = DateTime.now
Lotus::Utils::Kernel.BigDecimal(input) # => TypeError

# When Time
input = Time.now
Lotus::Utils::Kernel.BigDecimal(input) # => TypeError

# String that doesn't represent a big decimal
input = 'hello'
Lotus::Utils::Kernel.BigDecimal(input) # => TypeError

# Missing #respond_to?
input = BasicObject.new
Lotus::Utils::Kernel.BigDecimal(input) # => TypeError

Parameters:

  • arg (Object)

    the argument

Returns:

Raises:

  • (TypeError)

    if the argument can’t be coerced

See Also:

Since:

  • 0.3.0



421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/lotus/utils/kernel.rb', line 421

def self.BigDecimal(arg)
  case arg
  when ->(a) { a.respond_to?(:to_d) } then arg.to_d
  when Float, Complex, Rational
    BigDecimal(arg.to_s)
  when ->(a) { a.to_s.match(NUMERIC_MATCHER) }
    BigDecimal.new(arg)
  else
    raise TypeError.new "can't convert #{inspect_type_error(arg)}into BigDecimal"
  end
rescue NoMethodError
  raise TypeError.new "can't convert #{inspect_type_error(arg)}into BigDecimal"
end