Skip to content

Fix: float32 and float64 comparisions with EqualValues#1863

Open
snopan wants to merge 5 commits intostretchr:masterfrom
snopan:master
Open

Fix: float32 and float64 comparisions with EqualValues#1863
snopan wants to merge 5 commits intostretchr:masterfrom
snopan:master

Conversation

@snopan
Copy link
Copy Markdown

@snopan snopan commented Mar 17, 2026

Summary

This PR attempts to provide a solution to #1576 where converting float32 to float64 for comparison will fail due to differences in binary representation. Where

fmt.Println(float32(10.1))          // 10.1
fmt.Println(float64(10.1))          // 10.1
fmt.Println(float64(float32(10.1))) //10.100000381469727

This solution only allows comparison when float64 value has just as many decimal digits defined as float32. For example

fmt.Println(float32(10.123456))      // 10.123456
fmt.Println(float64(10.12345600000)) // 10.123456

But for 1.0 / 3.0, these are very different values for both float32 and float64.

fmt.Println(float32(1.0 / 3.0)) // 0.33333334
fmt.Println(float64(1.0 / 3.0)) // 0.3333333333333333

Because the float64 value has more decimal places defined than float32, they are not equal anyway.

playground

Changes

  • Added rounding logic for converted float32 value to remove the trailing non zero decimals after the 6th decimal place.
  • Added some variables to simplify logic which variable to convert and round

Motivation

When converting to float64, zeros are added the binary representation losing the accuracy of the original value. When we are comparing the float32 we only care about the digits that are accurate, which is why we remove the trailing digits. The choice to round to 6 digits was aligning to what I found in golang playground, float32 seems to round to 6 digits.

fmt.Println(float32(10.123456))  // 10.123456
fmt.Println(float32(10.1234567)) // 10.123457

playground

Related issues

Closes #1576

@snopan snopan marked this pull request as ready for review March 17, 2026 11:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

v1.9.0 breaks float comparisons with EqualValues

2 participants