Skip to content

Instantly share code, notes, and snippets.

@ryanveroniwooff
Created June 14, 2017 00:19
Show Gist options
  • Save ryanveroniwooff/7dcba11e056381384b6dc19dd3398793 to your computer and use it in GitHub Desktop.
Save ryanveroniwooff/7dcba11e056381384b6dc19dd3398793 to your computer and use it in GitHub Desktop.
Format ruby variable to us dollar
# use the .to_dollars method on any string and get appropriate
# dollar amount returned with two decimal places rounded to the hundreths
# format is for us dollar
class String
def to_dollars
d = self.decimals_present
return "$" + self + "00" if d == 0
return "$" + self + "0" if d == 1
return "$" + self if d == 2
return "$" + self.decimals[1] + '.' + self.round_decimals if d > 2
end
def round_decimals
d = self.decimals[0].split('')[0..1]
d[0] + (d[1].to_i + 1).to_s
end
def decimals
self.split('.').reverse
end
def decimals_present
self.split('.').reverse[0].length
end
end
float = 123.305 #=> 123.305
float.to_s.to_dollars #=> "$123.31"
int = 123 #=> 123
int.to_s.to_dollars #=> "$123.00"
str = "123.30" #=> "123.30"
str.to_dollars #=> "$123.30"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment