* * *

Author Topic: Issue with RoundTO  (Read 271 times)

Bazzao

  • Full Member
  • ***
  • Posts: 106
  • Pies are squared.
Issue with RoundTO
« on: September 11, 2017, 11:44:35 pm »
Issue with RoundTO

All I get is a 0 or a 1. Is there a bug?:

Code: Pascal  [Select]
  1. procedure MakeRoundTos;
  2. var I:integer; D:Double; ch:char;
  3. begin
  4.   Randomize;
  5.   for I:=1 to 20 do
  6.     begin
  7.       D:=Random()*1000;
  8.       writeln(D:8:3,'   ',RoundTo(D,3):8:3);
  9.     end;
  10.   ch:=Readkey;
  11. end;    
  12.  


B
Bazza

Lazarus 1.6.4 r54278 FPC 3.0.2 x86_64-win64-win32/win64
Windows 10, 7.

wp

  • Hero Member
  • *****
  • Posts: 3894
Re: Issue with RoundTO
« Reply #1 on: September 11, 2017, 11:58:13 pm »
RoundTo is a bit counterintuitive. Look at the help file:
Quote
function RoundTo(
  const AVAlue: Extended;
  const Digits: TRoundToRange
):Extended;


"RoundTo rounds the specified float AVAlue to the specified number of digits and returns the result. This result is accurate to "10 to the power Digits". It uses the standard Round function for this."

The key to understanding is the phrase "10 to the power Digits". This means that if you use the Digits parameter 3 the result is rounded to thousands (10^3). Since your numbers are only between 0 and 1000, the rounded result will be only 0 or 1000. Just increase the multiplier of the random() function from 1000 to 10000 to see that it always rounds to multiples of 1000.

I suppose you want to round the value to 3 decimal places. In this case the Digits parameter must be -3 (--> 10^-3).

Code: Pascal  [Select]
  1. program MakeRoundTos;
  2. uses
  3.   Math;
  4. //  SysUtils;
  5. var
  6.   I:integer;
  7.   D:Double;
  8.   ch:char;
  9. begin
  10.   Randomize;
  11.   for I:=1 to 20 do
  12.     begin
  13.       D := Random()*1000;
  14.       writeln(D:8:3, '   ', RoundTo(D,-3):8:3);   // <--- -3 instead of 3 !
  15.     end;
  16.   ReadLn;
  17. end.
Lazarus trunk / fpc 3.0.4 / all 32-bit on Win-10

Bazzao

  • Full Member
  • ***
  • Posts: 106
  • Pies are squared.
Re: Issue with RoundTO
« Reply #2 on: September 12, 2017, 12:06:01 am »
Thanks wp.

The help could be a bit more helpful. Including 2 examples, one positive and one negative.

It appears this is the opposite to Round*() in other languages, where a positive is used for decimals and negative for integers. And that is why help documentation should include opposite examples.

B
Bazza

Lazarus 1.6.4 r54278 FPC 3.0.2 x86_64-win64-win32/win64
Windows 10, 7.

wp

  • Hero Member
  • *****
  • Posts: 3894
Re: Issue with RoundTO
« Reply #3 on: September 12, 2017, 12:50:40 am »
Write a bug report and request it.
Lazarus trunk / fpc 3.0.4 / all 32-bit on Win-10

 

Recent

Get Lazarus at SourceForge.net. Fast, secure and Free Open Source software downloads Open Hub project report for Lazarus