Last active
July 15, 2018 13:24
-
-
Save bhaak/4e6e2ebb66ad16b4acd4aba81e50729d to your computer and use it in GitHub Desktop.
faster implementations of Rails' number_to_currency with hard coded formatting options
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
def fast_number_to_currency number | |
fix = number.fix | |
frac = number.frac.abs | |
"#{fix.to_i.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1'")}#{('%.2f' % frac)[1..-1]}" | |
end | |
def faster_number_to_currency1 number | |
integer = (number * 100).to_i | |
sign = integer.positive? ? '' : '-' | |
positive = integer.abs | |
return '0.00' if positive.zero? | |
fix = positive / 100 | |
frac1 = positive / 10 % 10 | |
frac2 = positive % 10 | |
string = "" | |
j = 0 | |
while fix > 0 do | |
if j == 3 | |
string.concat "'" | |
j = 0 | |
end | |
j += 1 | |
digit = (fix % 10) + 48 | |
string.concat digit | |
fix = fix / 10 | |
end | |
return "#{sign}#{string.reverse}.".concat(frac1+48).concat(frac2+48) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment