How do I use c# similar Math.Round
with MidpointRounding.AwayFromZero
in Delphi?
What will be the equivalent of:
double d = 2.125;
Console.WriteLine(Math.Round(d, 2, MidpointRounding.AwayFromZero));
Output: 2.13
In Delphi?
What you're looking for is SimpleRoundTo function in combination with SetRoundMode. As the documentations says:
SimpleRoundTo returns the nearest value that has the specified power of ten. In case
AValue
is exactly in the middle of the two nearest values that have the specified power of ten (above and below), this function returns:
The value toward plus infinity if
AValue
is positive.The value toward minus infinity if
AValue
is negative and the FPU rounding mode is not set to rmUp
Note that the second parameter to the function is TRoundToRange
which refers to exponent (power of 10) rather than number of fractional digis in .NET's Math.Round method. Therefore to round to 2 decimal places you use -2 as round-to range.
uses Math, RTTI;
var
LRoundingMode: TRoundingMode;
begin
for LRoundingMode := Low(TRoundingMode) to High(TRoundingMode) do
begin
SetRoundMode(LRoundingMode);
Writeln(TRttiEnumerationType.GetName(LRoundingMode));
Writeln(SimpleRoundTo(2.125, -2).ToString);
Writeln(SimpleRoundTo(-2.125, -2).ToString);
end;
end;
rmNearest
2,13
-2,13
rmDown
2,13
-2,13
rmUp
2,13
-2,12
rmTruncate
2,13
-2,13