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.
Instance Method Details
permalink #commas(places = nil) ⇒ Object
[View source]
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 |
permalink #group(places = 0, delim = ',') ⇒ Object
[View source]
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 |
permalink #int_if_whole ⇒ Object
Return an integer type, but only if the fractional part of self is zero
62 63 64 |
# File 'lib/fat_core/numeric.rb', line 62 def int_if_whole self.floor == self ? self.floor : self end |
permalink #secs_to_hms ⇒ Object
[View source]
66 67 68 69 70 71 72 73 74 75 |
# File 'lib/fat_core/numeric.rb', line 66 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 |
permalink #signum ⇒ Object
[View source]
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 |
permalink #tex_quote ⇒ Object
Allow erb documents can directly interpolate numbers
78 79 80 |
# File 'lib/fat_core/numeric.rb', line 78 def tex_quote to_s end |