Module: Hanami::Helpers::NumberFormattingHelper

Defined in:
gems/gems/hanami-helpers-1.3.0/lib/hanami/helpers/number_formatting_helper.rb

Overview

Number formatter

You can include this module inside your view and the view will have access all methods.

By including Hanami::Helpers::NumberFormattingHelper it will inject private method: format_number.

Since:

  • 0.2.0

Instance Method Summary collapse

Instance Method Details

#format_number(number, options = {}) ⇒ String (private)

Format the given number, according to the options

It accepts a number (Numeric) or a string representation.

If an integer is given, no precision is applied. For the rest of the numbers, it will format as a float representation. This is the case of: Float, BigDecimal, Complex, Rational.

If the argument cannot be coerced into a number, it will raise a TypeError.

Examples:

require 'hanami/helpers/number_formatting_helper'

class Checkout
  include Hanami::Helpers::NumberFormattingHelper

  def total
    format_number 1999.99
  end

  def euros
    format_number 1256.95, delimiter: '.', separator: ','
  end

  def visitors_count
    format_number '1000'
  end
end

view = Checkout.new

view.total
  # => "1,999.99"

view.euros
  # => "1.256,95"

view.visitors_count
  # => "1,000"

Parameters:

  • number (Numeric, String)

    the number to be formatted

Returns:

  • (String)

    formatted number

Raises:

  • (TypeError)

    if number can't be formatted

Since:

  • 0.2.0

def format_number(number, options = {})
  Formatter.new(number, options).format
end