How to Round a Float in Go
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
PS: I’ve got a fully interactive Golang course here if you’re interested in learning more about Go. It’s free to start!
Related Articles
The 7 Best Ways to Learn Golang and Find Your Inner Gopher
Feb 05, 2022 by Natalie Schooner - Computer science educator and technical writer
Golang was released in 2012, making it a relatively new language when compared to competitors like Python, which was released nearly two decades prior, yet it’s managed to stay ahead of the game as not only a coveted language by employers, but also loved by programmers.
How to Use Golang's Generics [Updated since 1.18]
Dec 06, 2021 by Lane Wagner - Boot.dev co-founder and backend engineer
Generics in Go have been released with Go 1.18! This is one of the most eagerly-awaited features since the release of the language. Many devs have gone so far as to say Go’s previous lack of generic types made the language too painful to use at all. Let’s dive into what generics are, why you might use them in your own projects, and how they work in Go.
Node.js vs Golang: Compared Over 6 Key Areas
Sep 23, 2021 by Meghan Reichenbach
In 2009, the computer science world was blessed with two powerful tools: Golang and Node.js.
Go vs C#: Compared Over 5 Key Areas
Sep 22, 2021 by Meghan Reichenbach
Golang and C# offer a unique mixture of similarities and differences, having both been inspired by the same language, C.