To round a number to the nearest integer in C#, you can use the built-in Math.Round()
function. This function takes a double
or decimal
number as input and returns the rounded result as either a double
or decimal
depending on the input type.
Here is an example usage:
main.cs66 chars3 lines
In this example, the variable number
holds the value 3.6
. The Math.Round()
function is called with number
as its input. The function returns 4.0
(a double
type), which is then cast to an int
to get the rounded integer value of 4
. The variable roundedNumber
now holds the value 4
.
Note that the Math.Round()
function has additional overloads that allow you to specify the number of digits to round to or choose how to handle rounding ties.
gistlibby LogSnag