Class: BigDecimal

Inherits:
Object show all
Defined in:
activesupport/lib/active_support/json/encoding.rb,
activesupport/lib/active_support/core_ext/object/duplicable.rb,
activesupport/lib/active_support/core_ext/big_decimal/conversions.rb

Constant Summary collapse

YAML_MAPPING =
{ 'Infinity' => '.Inf', '-Infinity' => '-.Inf', 'NaN' => '.NaN' }
DEFAULT_STRING_FORMAT =
'F'

Instance Method Summary collapse

Instance Method Details

#as_json(options = nil) ⇒ Object

A BigDecimal would be naturally represented as a JSON number. Most libraries, however, parse non-integer JSON numbers directly as floats. Clients using those libraries would get in general a wrong number and no way to recover other than manually inspecting the string with the JSON code itself.

That’s why a JSON string is returned. The JSON literal is not numeric, but if the other end knows by contract that the data is supposed to be a BigDecimal, it still has the chance to post-process the string and get the real value.

Use ActiveSupport.use_standard_json_big_decimal_format = true to override this behavior.



245
246
247
248
249
250
251
# File 'activesupport/lib/active_support/json/encoding.rb', line 245

def as_json(options = nil) #:nodoc:
  if finite?
    ActiveSupport.encode_big_decimal_as_string ? to_s : self
  else
    nil
  end
end

#encode_with(coder) ⇒ Object



8
9
10
11
# File 'activesupport/lib/active_support/core_ext/big_decimal/conversions.rb', line 8

def encode_with(coder)
  string = to_s
  coder.represent_scalar(nil, YAML_MAPPING[string] || string)
end

#to_dObject



15
16
17
# File 'activesupport/lib/active_support/core_ext/big_decimal/conversions.rb', line 15

def to_d
  self
end

#to_formatted_s(*args) ⇒ Object Also known as: to_s



21
22
23
24
25
26
27
28
# File 'activesupport/lib/active_support/core_ext/big_decimal/conversions.rb', line 21

def to_formatted_s(*args)
  if args[0].is_a?(Symbol)
    super
  else
    format = args[0] || DEFAULT_STRING_FORMAT
    _original_to_s(format)
  end
end