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
🌐
YourBasic
yourbasic.org › golang › round-float-2-decimal-places
Round float to 2 decimal places · YourBasic Go
x := 12.3456 fmt.Println(math.Floor(x*100)/100) // 12.34 (round down) fmt.Println(math.Round(x*100)/100) // 12.35 (round to nearest) fmt.Println(math.Ceil(x*100)/100) // 12.35 (round up)
🌐
gosamples
gosamples.dev › tutorials › round float to any precision in go
🎠 Round float to any precision in Go
April 24, 2023 - Full example of rounding a float to 2 decimal places: package main import ( "fmt" "math" ) func roundFloat(val float64, precision uint) float64 { ratio := math.Pow(10, float64(precision)) return math.Round(val*ratio) / ratio } func main() { number := 12.3456789 fmt.Println(roundFloat(number, ...
Discussions

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
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
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(2) float64?
Is it for display of the number, or you really want to lose the precision of your calculations? If it’s the former, you can use %.2f as the verb in your Printf. If it’s the latter, other redditors gave you example (by multiplying by 100, round, then divide), but allow me to question your reasoning? You are not using float for money calculation, I hope. More on reddit.com
🌐 r/golang
9
0
December 11, 2021
🌐
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.
🌐
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

🌐
Boot.dev
blog.boot.dev › golang › round-float-golang
How to Round a Float in Go | Boot.dev
November 13, 2022 - 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
🌐
Cockroach Labs
cockroachlabs.com › home › resources › blog › survey of rounding implementations in go
Survey of rounding implementations in Go
July 6, 2017 - There was a long thread on golang-nuts ... strconv: func RoundFloat(x float64, prec int) float64 { frep := strconv.FormatFloat(x, 'g', prec, 64) f, _ := strconv.ParseFloat(frep, 64) return f } This uses the 'g' format verb, which returns N digits total, not N digits after the decimal point...
Find elsewhere
🌐
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
🌐
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
🌐
w3tutorials
w3tutorials.net › blog › format-float-in-golang-html-template
How to Format Float64 to 2 Decimal Places in Go HTML Templates with Gin Gonic — w3tutorials.net
Next, build a function to format float64 values to 2 decimal places. We’ll use fmt.Sprintf with the %.2f format specifier, which rounds the value to the nearest hundredth (e.g., 123.456 → 123.46).
🌐
YourBasic
yourbasic.org › golang › convert-string-to-float
Convert between float and string · YourBasic Go
How to round a float to a string/float with 2 decimal places in Go. ... How to round a float64 to the nearest integer: round away from zero, round to even number, convert to an int type.
🌐
myCompiler
mycompiler.io › view › BywCTxGNWJ2
Go (Golang): HowTos: Round A Number to a Certain Number of Decimal Places (Go) - myCompiler
package main import ( "fmt" "math" ) func roundTo(num float64, precision int) float64 { scale := math.Pow(10, float64(precision)) return math.Round(num*scale) / scale } func main() { bytes := 26 kb := float64(bytes) / 1000 fmt.Printf("Raw Value: ...
🌐
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) }
🌐
LabEx
labex.io › tutorials › go-how-to-control-float-number-formatting-419737
How to control float number formatting | LabEx
package main import "fmt" func main() { // Declare a float32 variable var f32 float32 = 3.14159 // Declare a float64 variable var f64 float64 = 6.02214076e23 fmt.Println("float32 value:", f32) fmt.Println("float64 value:", f64) } ... Floating-point numbers are commonly used in various applications, such as scientific computations, financial calculations, and computer graphics, where precise representation of decimal values is crucial.
Top answer
1 of 1
5

The Go Programming Language Specification

Constants

Numeric constants represent exact values of arbitrary precision and do not overflow.

Implementation restriction: Although numeric constants have arbitrary precision in the language, a compiler may implement them using an internal representation with limited precision. That said, every implementation must:

  • Represent floating-point constants, including the parts of a complex constant, with a mantissa of at least 256 bits and a signed
    binary exponent of at least 16 bits.
  • Round to the nearest representable constant if unable to represent a floating-point or complex constant due to limits on precision.

These requirements apply both to literal constants and to the result of evaluating constant expressions.

Constant expressions

Constant expressions may contain only constant operands and are evaluated at compile time.

Constant expressions are always evaluated exactly; intermediate values and the constants themselves may require precision significantly larger than supported by any predeclared type in the language.

Implementation restriction: A compiler may use rounding while computing untyped floating-point or complex constant expressions; see the implementation restriction in the section on constants. This rounding may cause a floating-point constant expression to be invalid in an integer context, even if it would be integral when calculated using infinite precision, and vice versa.


Implement the RoundHalfUp function like the Go compiler does for math.Round(1.015*100) / 100. 1.015*100 is a untyped floating-point constant expression. Use the math/big package with at least 256 bits of precision. Go float64 (IEEE-754 64-bit floating-point) has 53 bits of precision.

For example, with 256 bits of precision (constant expression),

package main

import (
    "fmt"
    "math"
    "math/big"
)

func RoundHalfUp(x string) float64 {
    // math.Round(x*100) / 100
    xf, _, err := big.ParseFloat(x, 10, 256, big.ToNearestEven)
    if err != nil {
        panic(err)
    }
    xf100, _ := new(big.Float).Mul(xf, big.NewFloat(100)).Float64()
    return math.Round(xf100) / float64(100)
}

func main() {
    fmt.Println(RoundHalfUp("1.015"))
}

Playground: https://play.golang.org/p/uqtYwP4o22B

Output:

1.02

If we only use 53 bits of precision (float64):

xf, _, err := big.ParseFloat(x, 10, 53, big.ToNearestEven)

Playground: https://play.golang.org/p/ejz-wkuycaU

Output:

1.01
🌐
Go Forum
forum.golangbridge.org › getting help
New to GO- how it handles float precision 0.4 + 0.2 is 0.6 - Getting Help - Go Forum
October 31, 2024 - New to GO- how it handles float precision 0.4 + 0.2 = 0.6 I am new to chat and learning as value fact that Go is compiled, no classes, goto (exist). I am still learning some old school BASIC and QBASIC (as good foundat…