Created
June 14, 2017 00:19
-
-
Save ryanveroniwooff/7dcba11e056381384b6dc19dd3398793 to your computer and use it in GitHub Desktop.
Format ruby variable to us dollar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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