Skip to content
This repository
Browse code

Make number_to_human and number_with_precision work with negatives

  • Loading branch information...
commit e20012b64b2063b75cbf1acc57195f0c410987de 1 parent d717ff9
Santiago Pastorino authored September 05, 2010
4  actionpack/lib/action_view/helpers/number_helper.rb
@@ -260,7 +260,7 @@ def number_with_precision(number, options = {})
260 260
           if number == 0
261 261
             digits, rounded_number = 1, 0
262 262
           else
263  
-            digits = (Math.log10(number) + 1).floor
  263
+            digits = (Math.log10(number.abs) + 1).floor
264 264
             rounded_number = BigDecimal.new((number / 10 ** (digits - precision)).to_s).round.to_f * 10 ** (digits - precision)
265 265
           end
266 266
           precision = precision - digits
@@ -459,7 +459,7 @@ def number_to_human(number, options = {})
459 459
           raise ArgumentError, ":units must be a Hash or String translation scope."
460 460
         end.keys.map{|e_name| DECIMAL_UNITS.invert[e_name] }.sort_by{|e| -e}
461 461
 
462  
-        number_exponent = number != 0 ? Math.log10(number).floor : 0
  462
+        number_exponent = number != 0 ? Math.log10(number.abs).floor : 0
463 463
         display_exponent = unit_exponents.find{|e| number_exponent >= e }
464 464
         number  /= 10 ** display_exponent
465 465
 
2  actionpack/test/template/number_helper_test.rb
@@ -83,6 +83,7 @@ def test_number_with_delimiter_with_options_hash
83 83
   end
84 84
 
85 85
   def test_number_with_precision
  86
+    assert_equal("-111.235", number_with_precision(-111.2346))
86 87
     assert_equal("111.235", number_with_precision(111.2346))
87 88
     assert_equal("31.83", number_with_precision(31.825, :precision => 2))
88 89
     assert_equal("111.23", number_with_precision(111.2346, :precision => 2))
@@ -184,6 +185,7 @@ def test_number_to_human_size_with_custom_delimiter_and_separator
184 185
   end
185 186
 
186 187
   def test_number_to_human
  188
+    assert_equal '-123', number_to_human(-123)
187 189
     assert_equal '0', number_to_human(0)
188 190
     assert_equal '123', number_to_human(123)
189 191
     assert_equal '1.23 Thousand', number_to_human(1234)

0 notes on commit e20012b

Please sign in to comment.
Something went wrong with that request. Please try again.