Method: Numerals::Conversions.write

Defined in:
lib/numerals/conversions.rb

.write(number, options = {}) ⇒ Object

Convert Number to Numeral

write number, options={}

Valid options:

  • :rounding (a Rounding) (which defines output base as well)

  • :exact (exact input indicator)

Approximate mode:

If the input is treated as an approximation (which is the case for types such as Flt::Num, Float,… unless the :exact option is true) then no ‘spurious’ digits will be shown (digits that can take any value and the numeral still would convert to the original number if rounded to the same precision)

In approximate mode, if rounding is simplifying? (:short), the shortest representation which rounds back to the origina number with the same precision is used. If rounding is :free and the output base is the same as the number internal radix, the exact precision (trailing zeros) of the number is represented.

Exact mode:

Is used for ‘exact’ types (such as Integer, Rational) or when the :exact option is defined to be true.

The number is treated as an exact value, and converted according to Rounding. (in this case the :free and :short precision roundings are equivalent)

Summary

In result there are 5 basically diferent conversion modes. Three of them apply only to approximate values, so they are not available for all input types:

  • ‘Short’ mode, which produces an exact Numeral. Used when input is not exact and rounding precision is :short.

  • ‘Free’ mode, which produces an approximate Numeral. Used when input is not exact and rounding precision is :short.

  • ‘Fixed’ mode, which produces an approximate Numeral. Used when input isnot exact and rounding precision is limited.

The other two modes are applied to exact input, so they’re available for all input types (since all can be taken as exact with the :exact option):

  • ‘All’ mode, which produces an exact Numeral. Used when input is exact and rounding precision is :free (or :short).

  • ‘Rounded’ mode, which produces an approximate Numeral. Used when input is exact and rounding precision is limited.



102
103
104
105
106
107
# File 'lib/numerals/conversions.rb', line 102

def write(number, options = {})
  output_rounding = Rounding[options[:rounding] || Rounding[]]
  conversion = self[number.class, options[:type_options]]
  exact_input = conversion.exact?(number, options)
  conversion.write(number, exact_input, output_rounding)
end