Method: Hanami::Utils::Kernel.BigDecimal

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

.BigDecimal(arg, precision = ::Float::DIG) ⇒ BigDecimal

Coerces the argument to be a BigDecimal.

Examples:

Basic Usage

require 'hanami/utils/kernel'

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

BigDecimal Interface

require 'hanami/utils/kernel'

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

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

Unchecked exceptions

require 'hanami/utils/kernel'

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

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

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

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

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

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

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

# Missing #respond_to?
input = BasicObject.new
Hanami::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

[View source]

422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
# File 'lib/hanami/utils/kernel.rb', line 422

def self.BigDecimal(arg, precision = ::Float::DIG)
  case arg
  when NilClass # This is only needed by Ruby 2.6
    raise TypeError.new "can't convert #{inspect_type_error(arg)}into BigDecimal"
  when Rational
    arg.to_d(precision)
  when Numeric
    BigDecimal(arg.to_s)
  when ->(a) { a.respond_to?(:to_d) }
    arg.to_d
  else
    ::Kernel.BigDecimal(arg, precision)
  end
rescue NoMethodError
  raise TypeError.new "can't convert #{inspect_type_error(arg)}into BigDecimal"
end