00 Votes

Delphi: Round a number to thousands place (12345678 to 12345000)

Question by Mahdi | 2014-02-20 at 10:35

Hi. I'd like to round this number (12345678) to (12345000) in Delphi.

How can i do that? I search a lot but I didn't find anything. Also I don't know how to use (GetRoundMode).

Thanks :)

ReplyPositiveNegativeDateVotes
2Best Answer2 Votes

This cannot be done with the typical Delphi round() function like you can do it when rounding in PHP using a negative precision.

Just try the following code instead:

var
  k: integer;
begin
  k := 123456;
  k := round(k/1000) * 1000;
  showmessage(inntostr(k));  // 123000

If you always want to round down like in your example, you can use the function floor or trunc instead of round:

k := 12345678;
k := floor(k/1000) * 1000;  // k = 12345000

Because you brought me to that idea, I have just written a small function to round a number to any decimal place in Delphi. In this function you can use positive or negative values as a second parameter in order to round to a position after or before the decimal point.
2014-02-21 at 01:42

ReplyPositive Negative
22 Votes

Perhaps, also the build in function RoundTo from the unit Math can help you:

x:=RoundTo(12345, 3);  //12000

Or with setting the Round Mode:

SetRoundMode(rmTruncate);
x:=RoundTo(12345678, 3);  //12345000

SetRoundMode accepts the following parameters:

ModeMethod
rmNearestround (normal round)
rmDownfloor (always down)
rmUpceil (always up)
rmTruncatetrunc (cut value)

To prevent the function from rounding up, you can just use the rmTruncate mode.
2014-02-21 at 02:58

ReplyPositive Negative
Reply

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.