Skip to content

Instantly share code, notes, and snippets.

@Capncavedan
Created October 28, 2013 19:16
Show Gist options
  • Save Capncavedan/7202827 to your computer and use it in GitHub Desktop.
Save Capncavedan/7202827 to your computer and use it in GitHub Desktop.
Number to currency calculator, faster than ActiveSupport (due to no translation?)
def quick_number_to_currency(num)
left, right = sprintf("%.2f", num).split('.')
1 while left.sub!(/(\d)(\d\d\d)\b/, '\1' + ',' + '\2')
"$#{left}.#{right}"
end
it "turns 1000 into $1,000.00" do
@rt.quick_number_to_currency(1000).should eql("$1,000.00")
end
it "turns 10000 into $10,000.00" do
@rt.quick_number_to_currency(10000).should eql("$10,000.00")
end
it "turns 100000 into $100,000.00" do
@rt.quick_number_to_currency(100000).should eql("$100,000.00")
end
it "turns 1000000 into $1,000,000.00" do
@rt.quick_number_to_currency(1000000).should eql("$1,000,000.00")
end
it "turns 10000000 into $10,000,000.00" do
@rt.quick_number_to_currency(10000000).should eql("$10,000,000.00")
end
it "turns 100000000 into $100,000,000.00" do
@rt.quick_number_to_currency(100000000).should eql("$100,000,000.00")
end
it "turns 1000000000 into $1,000,000,000.00" do
@rt.quick_number_to_currency(1000000000).should eql("$1,000,000,000.00")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment