Created
March 23, 2018 08:48
-
-
Save phillipoertel/75ce9dcdc9744da710d9449e9169c846 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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