Skip to content

Commit a3cfa4a

Browse files
authored
Merge pull request rails#43098 from flavorjones/flavorjones-number-to-currency-detect-parse-failures
Fix number_to_currency regression in handling "-0.0"
2 parents 4d3a2c0 + 81175fb commit a3cfa4a

File tree

2 files changed

+12
-12
lines changed

2 files changed

+12
-12
lines changed

activesupport/lib/active_support/number_helper/number_to_currency_converter.rb

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,21 @@ class NumberToCurrencyConverter < NumberConverter # :nodoc:
88
self.namespace = :currency
99

1010
def convert
11-
number = self.number.to_s.strip
1211
format = options[:format]
1312

14-
if number.sub!(/^-/, "")
15-
number_f = number.to_f.abs
16-
if number_f == 0.0
17-
# likely an alternate input format that failed to parse.
18-
# see https://github.com/rails/rails/pull/39350
19-
format = options[:negative_format]
20-
else
21-
number_f *= 10**options[:precision]
22-
format = options[:negative_format] if number_f >= 0.5
13+
number_f = valid_float?
14+
if number_f
15+
if number_f.negative?
16+
number_f = number_f.abs
17+
format = options[:negative_format] if (number_f * 10**options[:precision]) >= 0.5
2318
end
19+
number_s = NumberToRoundedConverter.convert(number_f, options)
20+
else
21+
number_s = number.to_s.strip
22+
format = options[:negative_format] if number_s.sub!(/^-/, "")
2423
end
2524

26-
rounded_number = NumberToRoundedConverter.convert(number, options)
27-
format.gsub("%n", rounded_number).gsub("%u", options[:unit])
25+
format.gsub("%n", number_s).gsub("%u", options[:unit])
2826
end
2927

3028
private

activesupport/test/number_helper_test.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ def test_number_to_currency
8888
assert_equal("-$1,11", number_helper.number_to_currency("-1,11"))
8989
assert_equal("-$0,11", number_helper.number_to_currency("-0,11"))
9090
assert_equal("-$,11", number_helper.number_to_currency("-,11"))
91+
assert_equal("$0.00", number_helper.number_to_currency(-0.0))
92+
assert_equal("$0.00", number_helper.number_to_currency("-0.0"))
9193
end
9294
end
9395

0 commit comments

Comments
 (0)