Skip to content

Instantly share code, notes, and snippets.

@bhaak
Last active July 15, 2018 13:24
Show Gist options
  • Save bhaak/4e6e2ebb66ad16b4acd4aba81e50729d to your computer and use it in GitHub Desktop.
Save bhaak/4e6e2ebb66ad16b4acd4aba81e50729d to your computer and use it in GitHub Desktop.
faster implementations of Rails' number_to_currency with hard coded formatting options
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