02 Votes

Delphi/Lazarus: Function to Round Number to any Position after or before Decimal Point

Tutorial by Delphian | 2014-02-21 at 01:54

The normal Delphi or Lazarus Round Method can be used to round a float or extended value to an integer just like this:

var
  e: extended;
  i: integer;
begin
  e := 12.3456;
  i := round(e);  // 12

But what can we do if we would like to specify the rounding precision or if we would like to round in the other direction? So, for example to the decade place or the thousands digit? If we would like to make a 10 from a 12, a 100 from a 123 or a 20000 from a 21345? Or if we would like to keep some of the decimal places?

For this case, we can use the following function:

function RoundEx(const AInput: extended; APlaces: integer): extended;
var
  k: extended;
begin
  if APlaces = 0 then begin
    result := round(AInput);
  end else begin   
    if APlaces > 0 then begin
      k := power(10, APlaces);
      result := round(AInput * k) / k;
    end else begin
      k := power(10, (APlaces*-1));
      result := round(AInput / k) * k;
    end;
  end;
end;

Like Rounding in PHP, the RoundEx function can take positive or negative values depending on in which direction you would like to round. Here is an example:

var
  e, r: extended;
begin
  e := 123.456;
  r := RoundEx(e, 0);   // 123
  r := RoundEx(e, 1);   // 123.5
  r := RoundEx(e, 2);   // 123.46
  r := RoundEx(e, -1);  // 120
  r := RoundEx(e, -2);  // 100

The first parameter is our number, we would like to round. The second parameter is indicating the number of digits to which we would like to round.

Taking a 0 as a second parameter we get the same result as using the normal round function. With taking a positive number the function is cutting the desired number of decimal places from the number. Using a negative number, we can round to decade or thousands digit or any other higher decimal place.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

PHP: Rounding Numbers

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.