0

Someone know, how to do this with math only (without string conversions):

function Round_M(const aVal: Double): Double;
var
    x: Double;
    Str: string;
begin
    if aVal < 0 then
        x := aVal * 100 - 0.5
    else
        x := aVal * 100 + 0.5;

    Str := FloatToStr(x);

    if Pos(FormatSettings.DecimalSeparator, Str) > 0 then
        Str := Copy(Str, 1, Pos(FormatSettings.DecimalSeparator, Str) - 1);

    Result := StrToInt64(Str) * 0.01;
end;

It rounds to 0.01 and 0.005 always up. I try get same result with RoundTo, Trunc, Int, SimpleRoundTo... But f.ex 1.005 -> good rounded to 1.01 but 1.015 will be 1.02, and my solutions got 1.01. Same for 1.025, 1.035, 1.045, 1.055.

Dżyszla
  • 59
  • 8
  • Use a decimal type if you want to avoid issues with base 2 floating point represenatability. For instance, the closest double value to `0.01` is actually `0.01000000000000000020816681711721685132943093776702880859375`. But the closest double to `1.015` is `1.0149999999999999023003738329862244427204132080078125`, hence the behaviour that you see. And of course even that doesn't account for the various bugs in the Delphi libraries that convert from floating point to text. – David Heffernan Jan 28 '20 at 08:53
  • I know, but must works with Double. Decimal places can be other too - two in code above is only example. An no - there is no solution for this problem! I ask, how to replace this code, no how works floating-point type! – Dżyszla Jan 28 '20 at 09:01
  • 2
    Understanding how floating point types work is the key to understanding why what you are attempting to do is not possible. What you need to understand is why the statements in my previous comment are correct. Looking at a specific value, you need to appreciate that `1.015`, as one example of many, cannot be exactly represented. If you want to achieve your goal, you need to use a decimal type. – David Heffernan Jan 28 '20 at 09:34
  • If you are looking for the correct rounding, look at DecimalRounding (JH1) - https://cc.embarcadero.com/Item/21909 – Branko Jan 28 '20 at 14:03
  • @Branko I don't think that's going to help. – David Heffernan Jan 28 '20 at 15:01

0 Answers0