问题
I've got a Integer variable in Pascal. Is there any possible function I can use that can round that value to the nearest 1000, for example:
RoundTo(variable, 1000);
Does anything of the sort exist? Or is there another method I should try using?
Thanks!
回答1:
The general solution for this kind of problem is to scale before and after rounding, e.g.
y = 1000 * ROUND(x / 1000);
回答2:
Use RoundTo(variable, 3)
.
The second parameter specifies the digits you want to round to. Since you want to round to 1000 = 103 you need to specifiy 3
, not 1000
.
The documentation for RoundTo says:
function RoundTo(const AValue: Extended; const ADigit: TRoundToEXRangeExtended): Extended;
Rounds a floating-point value to a specified digit or power of ten using "Banker's rounding".
ADigit indicates the power of ten to which you want AValue rounded. It can be any value from –37 to 37 (inclusive).
The following examples illustrate the use of RoundTo:
RoundTo(1234567, 3) = 1235000
(I left out parts not relevant to your question)
Side-note: RoundTo
uses Banker's round, so RoundTo(500, 3) = 0
and RoundTo(1500, 3) = 2000
.
回答3:
x = 1000*(x/1000),
or x = x - (x mod 1000)
来源:https://stackoverflow.com/questions/15946123/how-can-i-round-an-integer-to-the-nearest-1000-in-pascal