Skip to content

Commit

Permalink
Fixed Numeric floating-point value loss of precision
Browse files Browse the repository at this point in the history
Fix #1667
  • Loading branch information
enchev committed Aug 23, 2024
1 parent b80a382 commit 08d7457
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion Radzen.Blazor/RadzenNumeric.razor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ bool IsNullable
};

#if NET7_0_OR_GREATER
private static TNum SumFloating<TNum>(TNum value1, TNum value2)
{
var decimalValue1 = (decimal)Convert.ChangeType(value1, TypeCode.Decimal);
var decimalValue2 = (decimal)Convert.ChangeType(value2, TypeCode.Decimal);

return (TNum)Convert.ChangeType(decimalValue1 + decimalValue2, typeof(TNum));
}

/// <summary>
/// Use native numeric type to process the step up/down while checking for possible overflow errors
/// and clamping to Min/Max values
Expand All @@ -116,7 +124,17 @@ private TNum UpdateValueWithStepNumeric<TNum>(TNum valueToUpdate, bool stepUp, d
return valueToUpdate;
}

var newValue = valueToUpdate + (stepUp ? step : -step);
TNum newValue = default(TNum);

if (typeof(TNum) == typeof(double) || typeof(TNum) == typeof(double?) ||
typeof(TNum) == typeof(float) || typeof(TNum) == typeof(float?))
{
newValue = SumFloating(valueToUpdate, (stepUp ? step : -step));
}
else
{
newValue = valueToUpdate + (stepUp ? step : -step);
}

if (Max.HasValue && newValue > TNum.CreateSaturating(Max.Value)
|| Min.HasValue && newValue < TNum.CreateSaturating(Min.Value)
Expand Down

0 comments on commit 08d7457

Please sign in to comment.