Skip to content

Commit

Permalink
Added roundup to Number
Browse files Browse the repository at this point in the history
  • Loading branch information
delano committed Dec 12, 2008
1 parent 104cacc commit 2258579
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions lib/scruffy/formatters.rb
Expand Up @@ -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
Expand All @@ -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.
Expand Down

0 comments on commit 2258579

Please sign in to comment.