Skip to content

Instantly share code, notes, and snippets.

@afomera
Created September 24, 2015 22:56
Show Gist options
  • Save afomera/44fe4e185e1f722d5112 to your computer and use it in GitHub Desktop.
Save afomera/44fe4e185e1f722d5112 to your computer and use it in GitHub Desktop.
#Pretend the sum is a big decimal and we want to conditionally append a 0 to replace
#the second dec place because ruby can chop the sec dec point
sum = "540.2"
def dec_split_sum(sum)
# Convert Sum to a string and then split it at the decimal point.
sum = sum.to_s.split('.')
if sum[1].length == 1
puts sum[0] + '.' + sum[1] + '0'
else
puts sum[0] + '.' + sum[1]
end
end
def dec_round_sum(sum)
# Not working example, doesn't add a 0
puts sum = sum.to_f.round(2)
end
def dec_format_sum(sum)
puts format("%.2f",sum)
end
dec_split_sum(sum)
dec_round_sum(sum)
dec_format_sum(sum)
@nynhex
Copy link

nynhex commented Sep 25, 2015

Consider the big decimal in your dec_round_sum method. The big decimal is basically a float so calling .to_f really doesn't do much.

But the format_sum is cool but in this instance we need to actually split dollars and cents to be used separately. At least in my use case. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment