Learn back-end development by writing real code

Boot.dev Blog ยป Golang ยป How to Round a Float in Go
Generated with Stable Diffusion. Prompt: 'large round thing, dark, 4k, fantasy'

How to Round a Float in Go

By Lane Wagner on Nov 13, 2022

Curated backend podcasts, videos and articles. All free.

If you're looking to become a backend developer, or just stay up-to-date with the latest backend technologies and trends, you found the right place. Subscribe below to get a copy of our newsletter, The Boot.dev Beat, each month in your inbox. No spam, no sponsors, totally free.

๐Ÿ”— Round float and format to string

If you’re rounding a floating point number in Go, it’s most likely you want to format it in a string. Use the built-in fmt.Sprintf() function.

heightInMeters := 1.76234
msg := fmt.Sprintf("Your height is: %.3f", heightInMeters)
// msg = "Your height is: 1.762"

๐Ÿ”— Round float and store in a float

Use math.Floor, math.Round and math.Ceil from the standard math package.

heightInMeters := 1.76234
roundedDown := math.Floor(x*100)/100 // 1.0
roundedToNearest := math.Round(x*100)/100 // 2.0
roundedUp := math.Ceil(x*100)/100 // 2.0

๐Ÿ”— Round float and store in an int

To store the result as an int, use the same method as before and then cast the result.

heightInMeters := 1.76234
roundedToNearest := int(math.Round(x*100)/100) // 2

Find a problem with this article?

Report an issue on GitHub