This class provides the functionality to format a Float according to certain rules. These rules determine how negative values are represented, how the fractional part is shown and how to structure the mantissa. The result is always a String.
The class uses the following parameters to control the formating. signPrefix: Prefix used for negative numbers. (String) signSuffix: Suffix used for negative numbers. (String) thousandsSeparator: Separator used after 3 integer digits. (String) fractionSeparator: Separator used between the inter part and the
fractional part. (String)
fractionDigits: Number of fractional digits to show. (Fixnum)
Create a new RealFormat object and define the formating rules.
# File lib/taskjuggler/RealFormat.rb, line 31 31: def initialize(args) 32: iVars = %( @signPrefix @signSuffix @thousandsSeparator 33: @fractionSeparator @fractionDigits ) 34: if args.is_a?(RealFormat) 35: # The argument is another RealFormat object. 36: iVars.each do |iVar| 37: instance_variable_set(iVar, args.instance_variable_get(iVar)) 38: end 39: elsif args.length == 5 40: # The argument is a list of values. 41: args.length.times do |i| 42: instance_variable_set(iVars[i], args[i]) 43: end 44: else 45: raise RuntimeError, "Bad number of parameters #{args.length}" 46: end 47: end
Converts the Float number into a String representation according to the formating rules.
# File lib/taskjuggler/RealFormat.rb, line 51 51: def format(number) 52: # Check for negative number. Continue with the absolute part. 53: if number < 0 54: negate = true 55: number = -number 56: else 57: negate = false 58: end 59: 60: # Determine the integer part. 61: intNumber = (number * (10 ** @fractionDigits)).round.to_i.to_s 62: if intNumber.length <= @fractionDigits 63: intNumber = '0' * (@fractionDigits - intNumber.length + 1) + intNumber 64: end 65: intPart = intNumber[0..-(@fractionDigits + 1)] 66: fracPart = 67: @fractionDigits > 0 ? '.' + intNumber[-(@fractionDigits)..1] : '' 68: 69: if @thousandsSeparator.empty? 70: out = intPart 71: else 72: out = '' 73: 1.upto(intPart.length) do |i| 74: out = intPart[-i, 1] + out 75: out = @thousandsSeparator + out if i % 3 == 0 && i < intPart.length 76: end 77: end 78: out += fracPart 79: # Now compose the result. 80: out = @signPrefix + out + @signSuffix if negate 81: out 82: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.