Round totals for currencies
Describes how to round amounts in Optimizely Customized Commerce orders.
Rounding is complex because different currencies use different numbers of decimal places.
The following methods return a value with the correct number of decimals, which is determined by the input currency.
- Currency.Round()
- Currency.Percentage()
- Money.Round()
Do not use Math.Round() for rounding. For example, do not use the following code.
var currentCurrency = “JPY”
Money itemPrice = new Money(Math.Round(lineItem.ListPrice, 2), currentCurrency);
If you currently use Math.Round, replace it like this.
var currentCurrency = “JPY”
Money itemPrice = new Money(lineItem.ListPrice, currentCurrency).Round();
Calculate and round an order total
After rounding, use the rounded value for all further totals. For example, here is the correct way to add a number.
var billingCurrency = order.Currency;
foreach (var item in order.GetAllLineItems())
{
var costWithoutDiscount = billingCurrency.Round(item.PlacedPrice * item.Quantity);
item.Properties["costWithoutDiscount"] = costWithoutDiscount;
}
Calculate taxes
To get an order‘s correctly-rounded tax amount, do not use the tax amount of individual items. Instead, follow this example.
var billingCurrency = order.Currency;
var saleTaxesAmount = taxes
.Where(x => x.TaxType == TaxType.SalesTax)
.Sum(x => billingCurrency.Percentage(itemPriceWithoutTax, x.Percentage));
In the above code, saleTaxesAmount is returned with a rounded value.
Note
Do not use billingCurrency.Percentage(itemPriceWithoutTax, x.Percentage) in other situations
Updated 9 months ago