The following code should work for a lot of simple use cases with relatively small numbers and small precision inputs. However, it may not work for some uses cases because of numbers overflowing out of the range of float64 numbers, as well as IEEE-754 rounding errors (other languages have this issue as well).

If you care about using larger numbers or need more precision, the following code may not work for your needs, and you should use a helper library (e.g. https://github.com/shopspring/decimal).

I picked up a one-liner round function from elsewhere, and also made toFixed() which depends on round():

func round(num float64) int {
    return int(num + math.Copysign(0.5, num))
}

func toFixed(num float64, precision int) float64 {
    output := math.Pow(10, float64(precision))
    return float64(round(num * output)) / output
}

Usage:

fmt.Println(toFixed(1.2345678, 0))  // 1
fmt.Println(toFixed(1.2345678, 1))  // 1.2
fmt.Println(toFixed(1.2345678, 2))  // 1.23
fmt.Println(toFixed(1.2345678, 3))  // 1.235 (rounded up)
Answer from David Calhoun on Stack Overflow
Discussions

math: add Round
What version of Go are you using (go version)? 1.8 What did you expect to see? A rounding method for floats in the standard library What did you see instead? There is no standard library method for rounding a float64 to int/int32 I would... More on github.com
🌐 github.com
38
April 24, 2017
How to round big.Float to two decimal places

https://play.golang.org/p/SDNoJTT2tsS

More on reddit.com
🌐 r/golang
8
5
June 13, 2018
go - Round all decimal points in Golang - Stack Overflow
I'm trying to unconventionally round all the digits in a float64 variable. For example: 3.4444445 --> 3.5 I want to do this without converting it into a string! More on stackoverflow.com
🌐 stackoverflow.com
How to round 2100.825 to 2100.83?

The problem is not with your program, it is that the float64 representation of 2100.825 is not exact. Try:

fmt.Printf("%4.24g",2100.825)
More on reddit.com
🌐 r/golang
12
3
June 20, 2017
🌐
gosamples
gosamples.dev › tutorials › round float to any precision in go
🎠 Round float to any precision in Go
April 24, 2023 - The difference from classical rounding ... round a float in this way, you must set the formatting verb %f as an argument to these functions with a precision value of %.nf where n specifies the precision, that is, the number of decimal places....
🌐
Boot.dev
blog.boot.dev › golang › round-float-golang
How to Round a Float in Go | Boot.dev
November 13, 2022 - 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 = ...
🌐
Cockroach Labs
cockroachlabs.com › home › resources › blog › survey of rounding implementations in go
Survey of rounding implementations in Go
July 6, 2017 - This discussion continued to post broken round implementations (bringing the number of broken implementations up to something above 8). But happily, the Go team has agreed to add math.Round in Go 1.10! Even more happily, someone has posted a working implementation. func Round(x float64) float64 { const ( mask = 0x7FF shift = 64 - 11 - 1 bias = 1023 ``` signMask = 1 << 63 fracMask = (1 << shift) - 1 halfMask = 1 << (shift - 1) one = bias << shift ) bits := math.Float64bits(x) e := uint(bits>>shift) & mask switch { case e < bias: // Round abs(x)<1 including denormals.
🌐
DEV Community
dev.to › natamacm › round-numbers-in-go-5c01
Round numbers in Go - DEV Community
May 10, 2020 - Go (golang) lets you round floating point numbers. To do so, you need to import the math module. The official math package provides methods for rounding math.Ceil() up and math.Floor() down. package main import ( "fmt" "math" ) func main(){ ...
🌐
Google Groups
groups.google.com › g › golang-nuts › c › JlUWmeDtkZY
keep just 2 decimal places in a float64
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/46cadc14-9c8e-4c3a-9c6b-d0af7b621061@googlegroups.com. ... Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... Even if fixed supports 7 decimal places, those 7 decimal places should have the same value (after rounding) as the result provided by math.Big.
🌐
Go Packages
pkg.go.dev › github.com › shopspring › decimal
decimal package - github.com/shopspring/decimal - Go Packages
April 12, 2024 - NewFromBigRat returns a new Decimal from a big.Rat. The numerator and denominator are divided and rounded to the given precision. ... d1 := NewFromBigRat(big.NewRat(0, 1), 0) // output: "0" d2 := NewFromBigRat(big.NewRat(4, 5), 1) // output: "0.8" d3 := NewFromBigRat(big.NewRat(1000, 3), 3) // output: "333.333" d4 := NewFromBigRat(big.NewRat(2, 7), 4) // output: "0.2857" ... NewFromFloat converts a float64 to Decimal.
Find elsewhere
🌐
GitHub
github.com › golang › go › issues › 20100
math: add Round · Issue #20100 · golang/go
April 24, 2017 - What version of Go are you using (go version)? 1.8 What did you expect to see? A rounding method for floats in the standard library What did you see instead? There is no standard library method for rounding a float64 to int/int32 I would...
Author   DavidR91
🌐
Go
go.dev › play › p › KNhgeuU5sT
Go Playground - The Go Programming Language
Common problems companies solve with Go · Stories about how and why companies use Go
🌐
Reddit
reddit.com › r/golang › how to round big.float to two decimal places
r/golang on Reddit: How to round big.Float to two decimal places
June 13, 2018 -

Hello, I'm couple of months into Go, but I'm struggling with a quite basic question. I need to precisely divide decimals and round them to two (or n) decimal places. I know there are external libraries to do calculations with decimals, but I'm looking to solve this with the standard library.

This is where I am so far: https://play.golang.org/p/i54VaI747nM

🌐
Medium
2h3ph3rd.medium.com › floating-point-numbers-in-go-cda41a7655c6
Floating Point Numbers in Go: Exploring Rounding Issues and Effective Strategies | by Francesco Pastore | Medium
December 1, 2023 - package main import ( "fmt" ) func main() { num := 0.125 rate := num * 100.0 fmt.Println("1:", rate) num = 0.14 rate = num * 100.0 fmt.Println("2:", rate) num = 0.1425 rate = num * 100.0 fmt.Println("3:", rate) } ... If you are skeptical about these results, you can copy the code into a file named main.go and then execute it using the command go run main.go · If this is your first encounter with floating-point numbers, it might seem a bit peculiar.
🌐
Socket Loop
socketloop.com › tutorials › golang-round-float-to-precision-example
Golang : Round float to precision example
September 28, 2015 - Colombia’s intercity bus network is extensive, affordable, and a practical alternative to flying. This guide explains how to compare terminals, choose reputable operators, buy tickets online or at stations, and plan a comfortable journey across the country.
🌐
Reddit
reddit.com › r/golang › how to round 2100.825 to 2100.83?
r/golang on Reddit: How to round 2100.825 to 2100.83?
June 20, 2017 -

Hi,

I try to round 2100.825 to 2100.83 but get always 2100.82. Here is the code

package main

import (
  "fmt"
  "math"
)

func main() {
  fmt.Println("Expecting 2100.83, but was:", round100(2100.825))
}

func round100(x float64) float64 {
  a := x * 100
  _, rem := math.Modf(a)
  fmt.Println("frac:", rem)
  if rem >= 0.5 {
    fmt.Println("ceil")
    a = math.Ceil(a)
  } else {
    fmt.Println("floor")
    a = math.Floor(a)
  }
  return a / 100
}

If I modify the number to 1100.825 it is properly rounded to 1100.83.

Where is the flaw? And what is the correct implementation of round100?

🌐
GolangSpot
golangspot.com › home › how to round a float number to decimal places in golang
How to Round a Float Number to Decimal Places in Golang - GolangSpot
September 27, 2023 - RoundFloat(344.9852241,4) – It will round a float number to 4 decimal places. You can find more topics about the Golang tutorials on the GolangSpot Home page.
🌐
GitHub
github.com › mhale › round
GitHub - mhale/round: A floating-point number rounding package for Go. · GitHub
RoundTo is a convenience wrapper for ToNearestEven, which rounds to a specified number of decimal places. value := round.RoundTo(1234.5678, 2) // value is 1234.57 · ToNearestEven rounds to the nearest integer value, with ties rounded to even integers. ... These links may be useful to learn about floating-point rounding modes.
Author   mhale