Permalink
Browse files

Added roundup to Number

  • Loading branch information...
1 parent 104cacc commit 2258579acfd0fc6799af522cbbd0f1ef4025f982 @delano delano committed Dec 12, 2008
Showing with 21 additions and 3 deletions.
  1. +21 −3 lib/scruffy/formatters.rb
View
24 lib/scruffy/formatters.rb
@@ -81,9 +81,11 @@ class Number < Base
#
# separator:: decimal separator. Defaults to '.'
# delimiter:: delimiter character. Defaults to ','
- # precision_limit:: upper limit for auto precision.
+ # precision_limit:: upper limit for auto precision. (Ignored if roundup is specified)
+ # roundup:: round up the number to the given interval
def initialize(options = {})
@precision = options[:precision] || :none
+ @roundup = options[:roundup] || :none
@separator = options[:separator] || '.'
@delimiter = options[:delimiter] || ','
@precision_limit = options[:precision_limit] || 4
@@ -107,16 +109,32 @@ def format(target, idx, options)
my_separator = @separator
my_separator = "" unless my_precision > 0
begin
- parts = number_with_precision(target, my_precision).split('.')
+ number = ""
+
+ if @roundup == :none
+ parts = number_with_precision(target, my_precision).split('.')
+ number = parts[0].to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{@delimiter}") + my_separator + parts[1].to_s
+ else
+ number = roundup(target.to_f, @roundup).to_i.to_s
+ end
- number = parts[0].to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1#{@delimiter}") + my_separator + parts[1].to_s
number
rescue StandardError => e
target
end
end
+
+
+ def roundup(target, nearest=100)
+ target % nearest == 0 ? target : target + nearest - (target % nearest)
+ end
+ def rounddown(target, nearest=100)
+ target % nearest == 0 ? target : target - (target % nearest)
+ end
end
+
+
# Currency formatter.
#
# Provides formatting for currencies.

0 comments on commit 2258579

Please sign in to comment.