Recent

Author Topic: Roundto - Can't get it to work  (Read 304 times)

JLWest

  • Hero Member
  • *****
  • Posts: 806
Roundto - Can't get it to work
« on: July 04, 2020, 07:29:01 pm »
 Var MPMin, MPHS, Wrk : Single;

    begin
     MPMin := (MPHs / 60);   {  = 8.71666622}
     WrK    := MPMin;
     MPMin :=   Roundto(Wrk);  {= 0}
 
     Tried this:

    MPMin := RoundTo( 8.71666622 , 2);   {= 0}                         
FPC 3.2.0, Lazarus IDE v2.0.4
 Windows 10 Pro 32-GB
 Intel i7 770K CPU 4.2GHz 32702MB Ram
GeForce GTX 1080 Graphics - 8 Gig
4.1 TB

wp

  • Hero Member
  • *****
  • Posts: 7392
Re: Roundto - Can't get it to work
« Reply #1 on: July 04, 2020, 07:40:38 pm »
The function RoundTo is a bit counter-intuitive because everybody calling RoundTo(x, 2) thinks that it rounds x to 2 decimal places. No, it rounds to multiples of 10 to the power of the second argument. In other words: 10^2 is 100, and thus RoundTo(x, 2) rounds to full hundreds, e.g. RoundTo(871.6666, 2) becomes 900, but RoundTo(8.71666, 2) becomes 0 because it is less than 100.

In order to round to two decimal places you round to multiples of 0.01 = 10^-2. therefore, you must call RoundTo(x, -2).
« Last Edit: July 04, 2020, 07:43:59 pm by wp »
Mainly Lazarus trunk / fpc 3.2.0 / all 32-bit on Win-10, but many more...

winni

  • Hero Member
  • *****
  • Posts: 1616
Re: Roundto - Can't get it to work
« Reply #2 on: July 04, 2020, 07:41:59 pm »
Hi!

Yes - that is correct.

roundTo (8.7,2) means: round to 100 - so it is zero
roundTo (8.7,1) means: round to 10 - so it is 10
roundTo (8.7,0) means: round to 1 - so it is 9

Everything as it should be.

Winni

JLWest

  • Hero Member
  • *****
  • Posts: 806
Re: Roundto - Can't get it to work
« Reply #3 on: July 04, 2020, 08:11:22 pm »
A "bit counter-intuitive"! I felt bad about posting the question. Now I feel better.

Thank you gentlemen.
FPC 3.2.0, Lazarus IDE v2.0.4
 Windows 10 Pro 32-GB
 Intel i7 770K CPU 4.2GHz 32702MB Ram
GeForce GTX 1080 Graphics - 8 Gig
4.1 TB

 

TinyPortal © 2005-2018