Skip to content

Instantly share code, notes, and snippets.

@pat
Last active December 22, 2015 01:29
Show Gist options
  • Select an option

  • Save pat/6397227 to your computer and use it in GitHub Desktop.

Select an option

Save pat/6397227 to your computer and use it in GitHub Desktop.
Reliably get the fixed format of a float in Ruby, rather than exponential. BUT: don't use an extraordinarily large number of decimal places, else you'll likely get more precision than you need.
# as a method
def fixed_format(float)
return float if float.to_s['e'].nil?
matches = float.to_s.scan(/(\d+)e\-(\d+)$/).first
# exponent + number of trailing digits
digits = matches.last.to_i + matches.first.length
("%0.#{digits}f" % float).gsub(/0+$/, '')
end
# or better, clearer, albeit a little more code: as a class
class FloatFormatter
PATTERN = /(\d+)e\-(\d+)$/
def initialize(float)
@float = float
end
def fixed
return float.to_s unless exponent_present?
("%0.#{decimal_places}f" % float).gsub(/0+$/, '')
end
private
attr_reader :float
def exponent_decimal_places
float.to_s[PATTERN, 1].length
end
def exponent_factor
float.to_s[PATTERN, 2].to_i
end
def exponent_present?
float.to_s['e']
end
def decimal_places
exponent_factor + exponent_decimal_places
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment