lib/hanami/helpers/number_formatting_helper.rb in hanami-helpers-0.5.0 vs lib/hanami/helpers/number_formatting_helper.rb in hanami-helpers-0.5.1

- old
+ new

@@ -132,11 +132,11 @@ # @see Hanami::Helpers::NumberFormatter::Formatter::DEFAULT_PRECISION def initialize(number, options) @number = number @delimiter = options.fetch(:delimiter, DEFAULT_DELIMITER) @separator = options.fetch(:separator, DEFAULT_SEPARATOR) - @precision = options.fetch(:precision, DEFAULT_PRECISION) + @precision = options.fetch(:precision, nil) end # Format number according to the specified options # # @return [String] formatted number @@ -179,11 +179,16 @@ # @raise [TypeError] if number can't be formatted # # @since 0.2.0 # @api private def to_str - to_number.to_s + number = to_number + if precision_requested_explicitly? + Kernel.format("%.#{precision}f", number) + else + number.to_s + end end # Numeric coercion # # @return [Numeric] coerced number @@ -201,19 +206,39 @@ else Utils::Kernel.Float(rounded_number) end end + # Returns precision with a fallback to default value + # + # @return [Numeric] precision + # + # @since 1.0.0 + # @api private + def precision + @precision || DEFAULT_PRECISION + end + + # Checks if precision was requested in options + # + # @return [TrueClass,FalseClass] the result of the check + # + # @since 1.0.0 + # @api private + def precision_requested_explicitly? + !@precision.nil? + end + # Round number in case we need to return a <tt>Float</tt> representation. # If <tt>@number</tt> doesn't respond to <tt>#round</tt> return the number as it is. # # @return [Float,Complex,Rational,BigDecimal] rounded number, if applicable # # @since 0.2.0 # @api private def rounded_number if @number.respond_to?(:round) - @number.round(@precision) + @number.round(precision) else @number end end end