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/RealFormat.rb, line 30 30: def initialize(args) 31: iVars = %( @signPrefix @signSuffix @thousandsSeparator 32: @fractionSeparator @fractionDigits ) 33: if args.is_a?(RealFormat) 34: # The argument is another RealFormat object. 35: iVars.each do |iVar| 36: instance_variable_set(iVar, args.instance_variable_get(iVar)) 37: end 38: elsif args.length == 5 39: # The argument is a list of values. 40: 0.upto(4) do |i| 41: instance_variable_set(iVars[i], args[i]) 42: end 43: else 44: raise RuntimeError, "Bad number of parameters #{args.length}" 45: end 46: end
Converts the Float number into a String representation according to the formating rules.
# File lib/RealFormat.rb, line 50 50: def format(number) 51: # Check for negative number. Continue with the absolute part. 52: if number < 0 53: negate = true 54: number = -number 55: else 56: negate = false 57: end 58: 59: # Determine the integer part. 60: intNumber = (number * (10 ** @fractionDigits)).round.to_i.to_s 61: if intNumber.length <= @fractionDigits 62: intNumber = '0' * (@fractionDigits - intNumber.length + 1) + intNumber 63: end 64: intPart = intNumber[0..-(@fractionDigits + 1)] 65: fracPart = 66: @fractionDigits > 0 ? '.' + intNumber[-(@fractionDigits)..1] : '' 67: 68: if @thousandsSeparator.empty? 69: out = intPart 70: else 71: out = '' 72: 1.upto(intPart.length) do |i| 73: out = intPart[-i, 1] + out 74: out = @thousandsSeparator + out if i % 3 == 0 && i < intPart.length 75: end 76: end 77: out += fracPart 78: # Now compose the result. 79: out = @signPrefix + out + @signSuffix if negate 80: out 81: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.