Module: Hanami::View::Helpers::NumberFormattingHelper

Extended by:
NumberFormattingHelper
Included in:
NumberFormattingHelper
Defined in:
lib/hanami/view/helpers/number_formatting_helper.rb

Overview

Helper methods for formatting numbers as text.

When using full Hanami apps, these helpers will be automatically available in your view templates, part classes and scope classes.

When using hanami-view standalone, include this module directly in your base part and scope classes, or in specific classes as required.

Examples:

Standalone usage

class BasePart < Hanami::View::Part
  include Hanami::View::Helpers::NumberFormattingHelper
end

class BaseScope < Hanami::View::Scope
  include Hanami::View::Helpers::NumberFormattingHelper
end

class BaseView < Hanami::View
  config.part_class = BasePart
  config.scope_class = BaseScope
end

Since:

  • 2.1.0

Defined Under Namespace

Classes: Formatter

Instance Method Summary collapse

Instance Method Details

#format_number(number, delimiter: DEFAULT_DELIMITER, separator: DEFAULT_SEPARATOR, precision: DEFAULT_PRECISION) ⇒ String

Returns a formatted string for the given number.

Accepts a number (Numeric) or a string representation of a number.

If an integer is given, applies no precision in the returned string. For all other kinds (Float, BigDecimal, etc.), formats the number as a float.

Raises an ArgumentError if the argument cannot be coerced into a number for formatting.

Examples:

format_number(1_000_000) # => "1,000,000"
format_number(Math::PI) # => "3.14"
format_number(Math::PI, precision: 4) # => "3.1416"
format_number(1256.95, delimiter: ".", separator: ",") # => "1.256,95"

Parameters:

  • number (Numeric, String)

    the number to be formatted

  • delimiter (String) (defaults to: DEFAULT_DELIMITER)

    hundred delimiter

  • separator (String) (defaults to: DEFAULT_SEPARATOR)

    fractional part separator

  • precision (String) (defaults to: DEFAULT_PRECISION)

    rounding precision

Returns:

  • (String)

    formatted number

Raises:

  • (ArgumentError)

    if the number can't be formatted

Since:

  • 2.1.0



86
87
88
# File 'lib/hanami/view/helpers/number_formatting_helper.rb', line 86

def format_number(number, delimiter: DEFAULT_DELIMITER, separator: DEFAULT_SEPARATOR, precision: DEFAULT_PRECISION) # rubocop:disable Layout/LineLength
  Formatter.call(number, delimiter: delimiter, separator: separator, precision: precision)
end