Class: Numeric
- Inherits:
-
Object
- Object
- Numeric
- Defined in:
- lib/fat_core/numeric.rb
Instance Method Summary collapse
- #commas(places = nil) ⇒ Object
- #group(places = 0, delim = ',') ⇒ Object
-
#int_if_whole ⇒ Object
Return an integer type, but only if the fractional part of self is zero.
- #secs_to_hms ⇒ Object
- #signum ⇒ Object
-
#tex_quote ⇒ Object
Allow erb documents can directly interpolate numbers.
-
#whole? ⇒ Boolean
Determine if this is a whole number.
Instance Method Details
#commas(places = nil) ⇒ Object
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/fat_core/numeric.rb', line 12 def commas(places = nil) # By default, use zero places for whole numbers; four places for # numbers containing a fractional part to 4 places. if places.nil? if self.abs.modulo(1).round(4) > 0.0 places = 4 else places = 0 end end group(places, ',') end |
#group(places = 0, delim = ',') ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/fat_core/numeric.rb', line 25 def group(places = 0, delim = ',') # Return number as a string with embedded commas # for nice printing; round to places places after # the decimal # Only convert to string numbers with exponent unless they are # less than 1 (to ensure that really small numbers round to 0.0) if self.abs > 1.0 && self.to_s =~ /e/ return self.to_s end str = self.to_f.round(places).to_s # Break the number into parts str =~ /^(-)?(\d*)((\.)?(\d*))?$/ neg = $1 || '' whole = $2 frac = $5 # Pad out the fractional part with zeroes to the right n_zeroes = [places - frac.length, 0].max frac += "0" * n_zeroes if n_zeroes > 0 # Place the commas in the whole part only whole = whole.reverse whole.gsub!(/([0-9]{3})/, "\\1#{delim}") whole.gsub!(/#{Regexp.escape(delim)}$/, '') whole.reverse! if frac.nil? || places <= 0 return neg + whole else return neg + whole + '.' + frac end end |
#int_if_whole ⇒ Object
Return an integer type, but only if the fractional part of self is zero
67 68 69 |
# File 'lib/fat_core/numeric.rb', line 67 def int_if_whole whole? ? self.floor : self end |
#secs_to_hms ⇒ Object
71 72 73 74 75 76 77 78 79 80 |
# File 'lib/fat_core/numeric.rb', line 71 def secs_to_hms frac = self % 1 mins, secs = self.divmod(60) hrs, mins = mins.divmod(60) if frac.round(5) > 0.0 "%02d:%02d:%02d.%d" % [hrs, mins, secs, frac.round(5) * 100] else "%02d:%02d:%02d" % [hrs, mins, secs] end end |
#signum ⇒ Object
2 3 4 5 6 7 8 9 10 |
# File 'lib/fat_core/numeric.rb', line 2 def signum if self > 0 1 elsif self < 0 -1 else 0 end end |
#tex_quote ⇒ Object
Allow erb documents can directly interpolate numbers
83 84 85 |
# File 'lib/fat_core/numeric.rb', line 83 def tex_quote to_s end |
#whole? ⇒ Boolean
Determine if this is a whole number.
61 62 63 |
# File 'lib/fat_core/numeric.rb', line 61 def whole? self.floor == self end |