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) Due to the quirks of floating point representation, these rounded values may be slightly off.
🌐
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

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
Printing two digits after decimal in go - Stack Overflow
I want to print two digits after decimal after rounding in GO language.. e.g 1.222225 should be printed as 1.22 1.356 should be printed as 1.36 How can i do it? More on stackoverflow.com
🌐 stackoverflow.com
Rounding value half-up to 2 decimal places in Go - Stack Overflow
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. More on stackoverflow.com
🌐 stackoverflow.com
go - How to round to at most 2 decimal places, if necessary using golang projection mongodb - Stack Overflow
In the Go programming language, you can use the fmt.Sprintf function to round a float to at most 2 decimal places. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Programming.Guide
programming.guide › go › round-float-2-decimal-places.html
Go: Round float to 2 decimal places | Programming.Guide
f := 12.3456 fmt.Println(math.Floor(f*100)/100, // 12.34 (round down) math.Round(f*100)/100, // 12.35 (round to nearest) math.Ceil(f*100)/100) // 12.35 (round up) Due to the quirks of floating point representation, these rounded values may be slightly off.
🌐
gosamples
gosamples.dev › tutorials › round float to any precision in go
🎠 Round float to any precision in Go
April 24, 2023 - In this way, by rounding the raised number to the nearest integer and then dividing, we get a number rounded to the specified decimal places. The roundFloat() is a floating-point rounding function, working as described above. The way it works is shown in the example: package main import ( "fmt" ...
🌐
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.
🌐
Boot.dev
blog.boot.dev › golang › round-float-golang
How to Round a Float in Go | Boot.dev
November 13, 2022 - Use the built-in fmt.Sprintf() function. heightInMeters := 1.76234 msg := fmt.Sprintf("Your height is: %.3f", heightInMeters) // msg = "Your height is: 1.762" Use math.Floor, math.Round and math.Ceil from the standard math package. heightInMeters ...
🌐
Cockroach Labs
cockroachlabs.com › home › resources › blog › survey of rounding implementations in go
Survey of rounding implementations in Go
July 6, 2017 - Many people would like something that, in addition to normal float -> int round, can round to N digits: round(12.345, 2) = 12.35. There was a long thread on golang-nuts about rounding, and one of the popular solutions was to use 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 Packages
pkg.go.dev › github.com › shopspring › decimal
decimal package - github.com/shopspring/decimal - Go Packages
April 12, 2024 - WARNING: this is dangerous for decimals with many digits, since many JSON unmarshallers (ex: Javascript's) will unmarshal JSON numbers to IEEE 754 double-precision floating point numbers, which means you can potentially silently lose precision. ... PowPrecisionNegativeExponent specifies the maximum precision of the result (digits after decimal point) when calculating decimal power. Only used for cases where the exponent is a negative number. This constant applies to Pow, PowInt32 and PowBigInt methods, PowWithPrecision method is not constrained by it. ... d1, err := decimal.NewFromFloat(15.2).PowInt32(-2) d1.String() // output: "0.0043282548476454" decimal.PowPrecisionNegativeExponent = 24 d2, err := decimal.NewFromFloat(15.2).PowInt32(-2) d2.String() // output: "0.004328254847645429362881"
🌐
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
🌐
Socket Loop
socketloop.com › tutorials › golang-display-float-in-2-decimal-points-and-rounding-up-or-down
Golang : Display float in 2 decimal points and rounding up or down
July 30, 2015 - To increase the precision, simply adjust the number from %0.2f to %0.#f. # being the number of digits to display the after the decimal point. Next, Golang math package lacks of functions to do rounding on float numbers.
🌐
OneLinerHub
onelinerhub.com › golang › how-to-format-float-to-2-decimal-places
Golang: How to format float to 2 decimal places - OneLinerHub
package main import "fmt" func main() { res := fmt.Sprintf("Float: %.2f", 123.2343) fmt.Println(res) }ctrl + c
🌐
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
🌐
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 - In the above golang program, we import the math package to use math.Round() function. RoundFloat function round the float number to 3 decimal places. I hope the above article helped you to round the float number to 2 decimal places or round a float number to 3 decimal places.
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
🌐
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.
🌐
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…
🌐
DEV Community
dev.to › natamacm › round-numbers-in-go-5c01
Round numbers in Go - DEV Community
May 10, 2020 - package main import ( "fmt" "math" ) func main() { fmt.Printf("%v\n", math.Round(1.4)) // Output: 1 fmt.Printf("%v\n", math.Round(-1.4)) // Output: -1 fmt.Printf("%v\n", math.Round(1.5)) // Output: 2 fmt.Printf("%v\n", math.Round(-1.5)) // Output: -1 fmt.Printf("%v\n", math.Round(1.6)) // Output: 2 fmt.Printf("%v\n", math.Round(-1.6)) // Output: -2 } ... We're a place where coders share, stay up-to-date and grow their careers.