Skip to content

Instantly share code, notes, and snippets.

@phillipoertel
Created March 23, 2018 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phillipoertel/75ce9dcdc9744da710d9449e9169c846 to your computer and use it in GitHub Desktop.
Save phillipoertel/75ce9dcdc9744da710d9449e9169c846 to your computer and use it in GitHub Desktop.
module Cm
module Shared
# Calculates a percentage of the amount passed in and returns it rounded to 2 decimals (i.e. cents),
# as a BigDecimal object.
#
# Some takeaways from "Invoices: How to properly round and calculate totals" (https://goo.gl/cHvuPa)
# - it is very easy to create invoices where numbers don't add up and a few cents are missing.
# - don't pass around unrounded values. Once you round, use the rounded value for all further totals.
# - the rounding of money amounts is *not* a matter of presentation, and should never happen in a view.
# - don't ever use the float data type in Ruby or MySQL for money
#
module CalculateMoneyPercentage
def calculate_money_percentage(amount, percentage)
(number_to_decimal(amount) * (number_to_decimal(percentage) / number_to_decimal(100))).round(2)
end
private
def number_to_decimal(amount)
precision = 10
BigDecimal.new(amount, precision)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment