In Delphi, you can use the following functions to round a number to the nearest integer:
Round
: This function rounds a number to the nearest integer. If the fractional part of the number is exactly 0.5, the function will round to the nearest even integer. For example,Round(3.5)
returns4
, andRound(4.5)
returns4
.Trunc
: This function truncates a number to the nearest integer. If the number is positive, it rounds down to the nearest integer. If the number is negative, it rounds up to the nearest integer. For example,Trunc(3.5)
returns3
, andTrunc(-3.5)
returns-3
.Int
: This function is similar toTrunc
, but it returns the integer value as aLongInt
type rather than as aDouble
type.
You can also use the System.Math.Round
function from the System
unit to round a number to a specific number of decimal places. This function takes a number and the number of decimal places to round to as arguments, and returns the rounded number.
Here is an example of how to use the System.Math.Round
function to round a number to two decimal places:
1 2 3 4 5 |
var RoundedNumber: Double; begin RoundedNumber := System.Math.Round(3.14159, 2); // RoundedNumber will be 3.14 end; |
Leave a Reply