From 9a05443d1e0a92132a44e3fe7d8e32e305499a40 Mon Sep 17 00:00:00 2001 From: Mike Dalessio Date: Wed, 23 Jun 2021 12:35:14 -0400 Subject: [PATCH] Fix number_to_currency to avoid negative format when displaying zero. This is a more-complete version of the fix in #37865 which originally addressed #37846. Also see context at #39350 with respect to alternate input formats. Closes #42577 --- .../number_helper/number_to_currency_converter.rb | 13 ++++++++++--- activesupport/test/number_helper_test.rb | 2 ++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb b/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb index c0efababa9..d1f0a4cad6 100644 --- a/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb @@ -11,9 +11,16 @@ module ActiveSupport number = self.number.to_s.strip format = options[:format] - if number.sub!(/^-/, "") && - (options[:precision] != 0 || number.to_f > 0.5) - format = options[:negative_format] + if number.sub!(/^-/, "") + number_f = number.to_f.abs + if number_f == 0.0 + # likely an alternate input format that failed to parse. + # see https://github.com/rails/rails/pull/39350 + format = options[:negative_format] + else + number_f *= 10**options[:precision] + format = options[:negative_format] if number_f > 0.5 + end end rounded_number = NumberToRoundedConverter.convert(number, options) diff --git a/activesupport/test/number_helper_test.rb b/activesupport/test/number_helper_test.rb index 9bdec994b7..78d6c23f83 100644 --- a/activesupport/test/number_helper_test.rb +++ b/activesupport/test/number_helper_test.rb @@ -79,6 +79,8 @@ module ActiveSupport assert_equal("1,234,567,890.50 - Kč", number_helper.number_to_currency("-1234567890.50", unit: "Kč", format: "%n %u", negative_format: "%n - %u")) assert_equal("0.00", number_helper.number_to_currency(+0.0, unit: "", negative_format: "(%n)")) assert_equal("$0", number_helper.number_to_currency(-0.456789, precision: 0)) + assert_equal("$0.0", number_helper.number_to_currency(-0.0456789, precision: 1)) + assert_equal("$0.00", number_helper.number_to_currency(-0.00456789, precision: 2)) assert_equal("$1,11", number_helper.number_to_currency("1,11")) assert_equal("$0,11", number_helper.number_to_currency("0,11")) assert_equal("$,11", number_helper.number_to_currency(",11"))