Skip to content

Commit

Permalink
SITE-50: Fixing rounding problems (#289)
Browse files Browse the repository at this point in the history
* Fixing rounding problems

* Refactoring rounding solution

* Simplifying code
  • Loading branch information
DemeSzabolcs authored Apr 12, 2023
1 parent 6bf017d commit 36721c2
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 4 deletions.
6 changes: 4 additions & 2 deletions src/Libraries/OrchardCore.Commerce.MoneyDataType/Amount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ public Amount(decimal value, CultureInfo? culture)
public Amount(decimal value, ICurrency? currency)
{
_currency = currency ?? MoneyDataType.Currency.UnspecifiedCurrency;
// The value is rounded to avoid storing more precision than what the currency supports.
Value = Math.Round(value, _currency.DecimalPlaces);
Value = value;
}

public bool Equals(Amount other) =>
Expand All @@ -81,6 +80,9 @@ public int CompareTo(Amount other)
return Value.CompareTo(other.Value);
}

public Amount GetRounded() =>
new(Math.Round(Value, Currency.DecimalPlaces), Currency);

private void ThrowIfCurrencyDoesntMatch(Amount other, string operation = "compare")
{
if (Currency.Equals(other.Currency)) return;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using OrchardCore.Commerce.MoneyDataType.Abstractions;
using OrchardCore.Commerce.MoneyDataType.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
Expand Down Expand Up @@ -33,4 +33,7 @@ public static Amount Sum(this IEnumerable<Amount> amounts)

return currency == null ? Amount.Unspecified : new Amount(sum, currency);
}

public static IEnumerable<Amount> Round(this IEnumerable<Amount> amounts) =>
amounts.Select(amount => amount.GetRounded());
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using OrchardCore.Commerce.Extensions;
using OrchardCore.Commerce.Models;
using OrchardCore.Commerce.MoneyDataType;
using OrchardCore.Commerce.MoneyDataType.Extensions;
using OrchardCore.Commerce.ViewModels;
using System.Collections.Generic;
using System.Linq;
Expand Down Expand Up @@ -94,7 +95,14 @@ private async Task<ShoppingCartViewModel> CreateShoppingCartViewModelAsync(
totals = lines.CalculateTotals().ToList();
}

model.Totals.AddRange(totals);
// The values are rounded to avoid storing more precision than what the currency supports.
foreach (var line in lines)
{
line.LinePrice = line.LinePrice.GetRounded();
line.UnitPrice = line.UnitPrice.GetRounded();
}

model.Totals.AddRange(totals.Round());
model.Headers.AddRange(headers);
model.Lines.AddRange(lines);

Expand Down

0 comments on commit 36721c2

Please sign in to comment.