To round a floating-point number to the nearest integer in Go, you can use the Round
function from the math
package. This function rounds a floating-point number to the nearest integer, and returns it as a float64
. To get an integer result, you can cast the rounded number to an integer using the int()
function. Here's an example:
main.go189 chars14 lines
In the example above, we declare a floating-point number x
with the value of 2.7
. We then use the Round
function to round this value to the nearest integer, which is 3
. We then cast the rounded value to an integer using the int()
function, and store it in the variable i
. We print out the original value, rounded value, and the integer value to verify that we've rounded x
to the nearest integer.
gistlibby LogSnag