Skip to content

Commit

Permalink
Optimize number helper
Browse files Browse the repository at this point in the history
  • Loading branch information
tinohager committed Sep 20, 2024
1 parent f7e5607 commit f3610ee
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Portalum.Zvt.UnitTest/NumberHelperTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,22 @@ namespace Portalum.Zvt.UnitTest
[TestClass]
public class NumberHelperTest
{
[TestMethod]
public void DecimalToBcd_Convert()
{
var amount = 0M;

for (var i = 0M; i < 100; i += 0.01M)
{
amount += i;

var bcdBytes = NumberHelper.DecimalToBcd(amount);
var newAmount = NumberHelper.BcdToDecimal(bcdBytes);

Assert.AreEqual(amount, newAmount);
}
}

[TestMethod]
public void DecimalToBcd_CommercialRoundOff_Successful()
{
Expand Down
26 changes: 26 additions & 0 deletions src/Portalum.Zvt/Helpers/NumberHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,32 @@ public static byte[] DecimalToBcd(decimal value, int length = 6)
return data.Reverse().ToArray();
}

/// <summary>
/// Convert Binary Coded Decimal to decimal
/// </summary>
/// <param name="bcdBytes"></param>
/// <returns></returns>
public static decimal BcdToDecimal(byte[] bcdBytes)
{
long result = 0;

foreach (var bcdByte in bcdBytes)
{
var highNibble = (bcdByte >> 4) & 0xF;
var lowNibble = bcdByte & 0xF;

if (highNibble > 9 || lowNibble > 9)
{
throw new ArgumentException("Invalid BCD-Format");
}

result = result * 10 + highNibble;
result = result * 10 + lowNibble;
}

return result / 100m;
}

/// <summary>
/// Convert int to Binary Coded Decimal
/// </summary>
Expand Down

0 comments on commit f3610ee

Please sign in to comment.