Class: BigDecimal
- Inherits:
-
Object
- Object
- BigDecimal
- Defined in:
- lib/ecraft/extensions/bigdecimal.rb
Overview
This extension assists BigDecimals coming out of Sequel resultsets with displaying as integers.
By default, BigDecimal objects serialized to JSON or string format have two defects:
- They get serialized in scientific notation (i.e.
1gets serialized as0.1E1). - Even if you use the
to_s('F')approach,1will get converted to1.0. This is useful to force the data to be converted to aFloatnumber if deserialized, but it causes practical problems since field like the M3 company number is normally stored in aDECIMAL(3)field in the database. With libraries like Sequel, this causes the data coming out from the database to be stored in aBigDecimal, even though it is really just a large integer.
For our .NET-based applications to be able to parse such fields to an int field, we needed to strip away the .0 part so that
BigDecimal(1).to_s becomes simply "1".
More details and history around this can be found in this discussion: https://github.com/ecraft/ecraft-extensions/pull/1
Instance Method Summary collapse
-
#to_json(*_a) ⇒ String
Converts this object to JSON form, in the simplest string form possible, either looking like a
FloatorFixnum. -
#to_s(s = nil) ⇒ String
Converts this object to the simplest string form possible, either looking like a
FloatorFixnum. -
#to_s_original ⇒ Object
The original (non-patched)
to_simplementation.
Instance Method Details
#to_json(*_a) ⇒ String
Converts this object to JSON form, in the simplest string form possible, either looking like a Float or Fixnum.
Values without any fraction digits will use Fixnum form, where values with a fractional part will use Float form.
26 27 28 |
# File 'lib/ecraft/extensions/bigdecimal.rb', line 26 def to_json(*_a) to_s end |
#to_s(s = nil) ⇒ String
Converts this object to the simplest string form possible, either looking like a Float or Fixnum.
Values without any fraction digits will use Fixnum form, where values with a fractional part will use Float form.
37 38 39 40 41 42 43 |
# File 'lib/ecraft/extensions/bigdecimal.rb', line 37 def to_s(s = nil) if s.nil? to_s_original('F').gsub(/\.0$/, '') else to_s_original(s) end end |
#to_s_original ⇒ Object
The original (non-patched) to_s implementation.
19 |
# File 'lib/ecraft/extensions/bigdecimal.rb', line 19 alias to_s_original to_s |