Skip to content

Instantly share code, notes, and snippets.

@ShadowBelmolve
Created March 14, 2009 21:10
Show Gist options
  • Save ShadowBelmolve/79182 to your computer and use it in GitHub Desktop.
Save ShadowBelmolve/79182 to your computer and use it in GitHub Desktop.
# Money.new(12345678901).to_real => "123.456.789,01"
def to_real
return "0,00" if cents == 0
tmp_money = cents.to_s.split(//)
tmp_cents = tmp_money.pop(2).to_s
if tmp_money.empty?
return ("%.2f" % (tmp_cents.to_i / 100.0)).gsub(".",",")
elsif tmp_money.length <= 3
return "#{tmp_money},#{tmp_cents}"
end
tmp_start = tmp_money.to_s.length % 3
tmp_start = tmp_money.shift(tmp_start).to_s
tmp_money2 = []
tmp_money.to_s.scan(/\d{3}/).each do |v|
tmp_money2 += [v]
end
if tmp_start.empty?
return "#{tmp_money2.join('.')},#{tmp_cents}"
else
return "#{tmp_start}.#{tmp_money2.join('.')},#{tmp_cents}"
end
end
irb(main):004:0> Money.new(1).to_real
=> "0,01"
irb(main):005:0> Money.new(12).to_real
=> "0,12"
irb(main):006:0> Money.new(123).to_real
=> "1,23"
irb(main):007:0> Money.new(1234).to_real
=> "12,34"
irb(main):008:0> Money.new(12345).to_real
=> "123,45"
irb(main):009:0> Money.new(123456).to_real
=> "1.234,56"
irb(main):010:0> Money.new(1234567).to_real
=> "12.345,67"
irb(main):011:0> Money.new(12345678).to_real
=> "123.456,78"
irb(main):012:0> Money.new(123456789).to_real
=> "1.234.567,89"
irb(main):013:0> Money.new(1234567890).to_real
=> "12.345.678,90"
irb(main):014:0> Money.new(12345678901).to_real
=> "123.456.789,01"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment