8

I just discovered that a software I have to reimplement uses extensivelly System.Round(). The problem is that this function uses "Bankers rounding" and the behaviour can not be changed like in Math.RoundTo() (rmDown,rmUp,rmNearest,rmTruncate).

I have to change the behaviour to "normal rounding" (12.5 -> 13 NOT 12.5 -> 12)... So I would like to override System.Round() globally. I want to do this, because Round() is used so many times and I do not want to change them all manually.

How is this possible?

4
  • 3
    According to docwiki.embarcadero.com/Libraries/XE2/en/System.Round the behaviour of System.round can indeed be set.
    – RobS
    Jun 7, 2013 at 8:42
  • 9
    You can just make new unit with published function Round(extended):extended, include this unit into uses section of every of your source files and recompile. If you did not use fully-qualified name (and almost no one do it for ubiquitous RTL function) then on e-compilation your new function would be more visible than System.Round. Changing global behaviour might have straneg consequences for some 3rd-party code in your program, Jun 7, 2013 at 9:14
  • Agree - this is the simplest approach. +1
    – Hugh Jones
    Jun 7, 2013 at 9:19
  • @RobS good information +1. Only thing is - not one of the options is 'Normal' rounding as the OP has it.
    – Hugh Jones
    Jun 7, 2013 at 11:29

4 Answers 4

14

WARNING: Although the answer below addresses the question that was asked, I would recommend that nobody ever uses it. If you want to perform rounding differently from Round then write and call a dedicated function.


You can use a runtime code hook to change the implementation of Round.

The wrinkle is that it's a little tricky to get hold of the address of the Round function though because it is an intrinsic. You also have to be careful to follow the calling convention used. The input value is passed in the x87 stack register ST(0) and the return value is a 64 bit integer in EDX:EAX.

Here's how to do it.

procedure PatchCode(Address: Pointer; const NewCode; Size: Integer);
var
  OldProtect: DWORD;
begin
  if VirtualProtect(Address, Size, PAGE_EXECUTE_READWRITE, OldProtect) then 
  begin
    Move(NewCode, Address^, Size);
    FlushInstructionCache(GetCurrentProcess, Address, Size);
    VirtualProtect(Address, Size, OldProtect, @OldProtect);
  end;
end;

type
  PInstruction = ^TInstruction;
  TInstruction = packed record
    Opcode: Byte;
    Offset: Integer;
  end;

procedure RedirectProcedure(OldAddress, NewAddress: Pointer);
var
  NewCode: TInstruction;
begin
  NewCode.Opcode := $E9;//jump relative
  NewCode.Offset := 
    NativeInt(NewAddress)-NativeInt(OldAddress)-SizeOf(NewCode);
  PatchCode(OldAddress, NewCode, SizeOf(NewCode));
end;

function System_Round: Pointer;
asm
  MOV     EAX, offset System.@Round
end;

procedure _ROUND;
asm
        { ->    FST(0)  Extended argument       }
        { <-    EDX:EAX Result                  }

        // your implementation goes here
end;

initialization
  RedirectProcedure(System_Round, @_ROUND);

If you'd rather implement your version in Pascal than asm then you need to adapt the non-standard calling convention of _ROUND to the standard Delphi calling convention. Like this:

function MyRound(x: Extended): Int64;
begin
  // your implementation goes here
end;

procedure _ROUND;
var
  x: Extended;
asm
        { ->    FST(0)  Extended argument       }
        { <-    EDX:EAX Result                  }

        FSTP    TBYTE PTR [x]
        CALL    MyRound
end;

Note that I have assumed here that your program is targeting 32 bit. If you need to target 64 bit then the principles are much the same, but the details obviously differ.

5
  • 1
    @Smasher Ha, thanks! There are huge amounts of such things. Runtime code hooking always looks cleverer than it really is. The trick with System_Round is something I learnt from madshi's madExcept. Nothing original here at all. Jun 7, 2013 at 9:21
  • 1
    @DavidHeffernan - it is still encyclopaedic knowledge, even if you don't think its original
    – Hugh Jones
    Jun 7, 2013 at 9:25
  • 1
    @HughJones: yes, knowing where to find the stuff you once heard/read about is a great asset for anyone in our profession. Jun 7, 2013 at 9:40
  • Thanks David! Finally I had to to through the code and changed Round() to x := Int(y + 0.5) (this works just for pos. numbers!). But thanks a lot for your solution anyway (Marked it as my accepted answer, because it answers my inital question)!
    – Michael
    Jun 7, 2013 at 16:10
  • 1
    That's liable to be too indiscriminate. Surely there will be other parts of a program, perhaps supplied by third-party code, that relies on the built-in behavior of Round. ;) Jun 7, 2013 at 17:53
7
UNIT MathRound;

INTERFACE

FUNCTION ROUND(X : Extended) : Int64;

IMPLEMENTATION

FUNCTION ROUND(X : Extended) : Int64;
  BEGIN
    Result:=TRUNC(X+0.5)
  END;

END.

If you save the above in MathRound.PAS i your project's directory, then include this unit in your source files, you will have a mathematical ROUND function instead of the banker's rounding that is implemented by default.

It'll round off -12.5 to -12 (ie. always rounding towards zero for .5 values) and -12.1 to -11. If you want a more "Logical" rounding, you should use this line instead:

  IF X<0.0 THEN Result:=-TRUNC(ABS(X)+0.5) ELSE Result:=TRUNC(X+0.5)

as the function body.

This will result in

ROUND(12.5) = 13
ROUND(12.1) = 12
ROUND(-12.5)= -13
ROUND(-12.1)= -12
1
  • IMHO this is the simplest and cleanest solution
    – user497849
    Jun 7, 2013 at 22:47
1

You're concerned about the time and effort required to manually change all your existing Round calls to call something else. So don't change them manually. Use a tool to automate it. For example, you could use sed.

sed -i -e "s/\bRound\b/BiasedRoundAwayFromZero/g" *.pas

With that change, your code is now explicit about what rounding it uses. It doesn't require everyone reading your code to know that a patch was applied elsewhere in the code to affect the global behavior of standard functions. It also doesn't affect code you link to from other libraries, which might rely on the standard behavior of Round and be broken by a global change.

7
  • 1
    That's liable to be too indiscriminate. Surely there will be other uses of the word "round" in the code. Jun 7, 2013 at 17:28
  • I wonder which is likely to be greater, @David, the number of times the standalone word Round appears in code when not referring to a function, or the number of times System.Round is called anywhere in a program (not just the project's source code) and required to use the default rounding behavior. And which is harder to detect? I postulate that it's the latter in both cases. Jun 7, 2013 at 17:54
  • I was thinking more of the comments. Very easy to detect System.Round of course. Unlikely to be other functions named round. Watch out for methods too. Jun 7, 2013 at 18:16
  • i guess that before doing substitutions one should try to get some statistics how often and in which part of code he uses "random" word. I wish Delphi had syntax-aware search and replace. Or is it called "refactoring" maybe ? In general, maybe those doubts are unbased, but i would also be wary of changing way too many words, including not only comments but GUI text literals as well. Jun 7, 2013 at 18:18
  • Yes, @Arioch, Delphi does come with a rename refactoring operation. I'm not sure it would work here, though, since I think it will recognize that this Round is System.Round, and ultimately fail because it can't apply the change to the function declaration. However, if the simple text substitution inadvertently changes another function named Round, the rename refactor could easily revert the change afterward. How many GUI text literals appear in your .pas files, how often do you use the word Round in them, and how fast would you notice if your GUI said the wrong thing? Jun 7, 2013 at 18:40
0

// bankers round omzeilen

function RoundN(X: double): double;
const
  cFuncName = 'RoundN';
begin
  Result := Trunc(X + Frac(X));
end;
2
  • 2
    Hi and welcome to SO. StackOverflow.com is an english site. Please always provide english descriptions to your code, questions and answers. Your answer must be edited to contain only english text.
    – Hexfire
    Jan 18, 2018 at 13:47
  • 1
    This is not what the OP asked. This doesn't override the Round method Jan 18, 2018 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.