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
Come to the dark side
Regards and sorry for the interruption, Lane here! I built Boot.dev to give you a place to learn back-end development the...hard way? I mean easy? Maybe the "heasy" way? I don't know.
It's hard because you will have to write code... like a metric ton of code. It's easy because my courses have a built-in game that's pretty darn fun. Give it a try.
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