# Golang : Compare floating-point numbers

Tags : golang float round-precision comparison

It has been a while since I need to compare two float numbers. Golang's `math/big`

package has function to compare floating-point numbers. Bear in mind that comparing float numbers can be tricky because most floating point numbers will end up imprecise due to rounding errors. What most people will do is to ignore the imprecision if it is small enough.

So, is the a way to compare two float numbers in Golang? Yes, see this example code :

```
package main
import (
"fmt"
"math/big"
)
func main() {
// change these value and play around
float1 := 123.4568
float2 := 123.45678
// convert float to type math/big.Float
var bigFloat1 = big.NewFloat(float1)
var bigFloat2 = big.NewFloat(float2)
fmt.Printf("Big Float1 : %0.5f \n", bigFloat1)
fmt.Printf("Big Float2 : %0.5f \n", bigFloat2)
// compare bigFloat1 to bigFloat2
result := bigFloat1.Cmp(bigFloat2)
// -1 if x < y
if result < 0 {
fmt.Println("bigFloat 1 less than bigFloat2")
}
// 0 if x == y
if result == 0 {
fmt.Println("bigFloat 1 equals to bigFloat2")
}
// +1 if x > y
if result > 0 {
fmt.Println("bigFloat 1 more than bigFloat2")
}
}
```

Output :

Big Float1 : 123.45680

Big Float2 : 123.45678

bigFloat 1 more than bigFloat2

Good to know, see http://floating-point-gui.de/errors/comparison/

Reference :

#### See also : Golang : Round float to precision example

Tags : golang float round-precision comparison

##### By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.

#### Advertisement

#### Tutorials

+16.7k Golang : Strings to lowercase and uppercase example

+7.1k Golang : Convert seconds to minutes and remainder seconds

+6.6k Golang : List objects in AWS S3 bucket

+1.2k Golang : Oanda bot with Telegram and RSI example

+4.9k Golang : Generate random integer or float number

+3.6k Golang : Simple file scaning and remove virus example

910 Golang : Calculate pivot points for a cross

+3k Golang : Select region of interest with mouse click and crop from image

+2k Golang : Break string into a slice of characters example

+1.8k Golang : How to convert strange string to JSON with json.MarshalIndent

533 Golang : Get FX sentiment from website example

+2.3k Golang : What is StructTag and how to get StructTag's value?