diff --git a/lib/liquid/standardfilters.rb b/lib/liquid/standardfilters.rb index afcf479e..5d859a22 100644 --- a/lib/liquid/standardfilters.rb +++ b/lib/liquid/standardfilters.rb @@ -391,6 +391,12 @@ module Liquid raise Liquid::FloatDomainError, e.message end + def format(input, n = 2, thousands = ',', decimal = '.') + return input if (precision = Utils.to_number(n).to_i) < 0 + whole_part, decimal_part = Kernel.format("%.#{precision}f", Utils.to_number(input)).split('.') + [whole_part.gsub(/(\d)(?=\d{3}+$)/, "\\1#{thousands}"), decimal_part].compact.join(decimal.to_s) + end + def ceil(input) Utils.to_number(input).ceil.to_i rescue ::FloatDomainError => e diff --git a/test/integration/standard_filter_test.rb b/test/integration/standard_filter_test.rb index 60909510..45e6e59f 100644 --- a/test/integration/standard_filter_test.rb +++ b/test/integration/standard_filter_test.rb @@ -610,6 +610,23 @@ class StandardFiltersTest < Minitest::Test assert_template_result "4", "{{ price | round }}", 'price' => NumberLikeThing.new(4.3) end + def test_format + assert_template_result "4.60", "{{ input | format }}", 'input' => 4.6 + assert_template_result "4.30", "{{ '4.3' | format }}" + assert_template_result "4.56", "{{ input | format: 2 }}", 'input' => 4.5612 + assert_template_result "5", "{{ price | format: 0 }}", 'price' => NumberLikeThing.new(4.6) + assert_template_result "4", "{{ price | format: 0 }}", 'price' => NumberLikeThing.new(4.3) + assert_template_result "4.30", "{{ price | format: 2 }}", 'price' => NumberLikeThing.new(4.3) + assert_template_result "5.0000000", "{{ price | format: 7 }}", 'price' => 5 + assert_template_result "50", "{{ price | format: -1 }}", 'price' => 50 + assert_template_result "50", "{{ price | format: A }}", 'price' => 50 + assert_template_result "50.00", "{{ price | format: '2e' }}", 'price' => 50 + assert_template_result "50,000,000", "{{ price | format: 0 }}", 'price' => 50000000 + assert_template_result "50,000,000.00", "{{ price | format }}", 'price' => 50000000 + assert_template_result "50000000.00", "{{ price | format: 2, '', '.'}}", 'price' => 50000000 + assert_template_result "50$000$000#00", "{{ price | format: 2, '$', '#'}}", 'price' => 50000000 + end + def test_ceil assert_template_result "5", "{{ input | ceil }}", 'input' => 4.6 assert_template_result "5", "{{ '4.3' | ceil }}"