Skip to content

Commit

Permalink
test: verify no precision loss when using float64
Browse files Browse the repository at this point in the history
  • Loading branch information
rootulp committed Nov 10, 2023
1 parent 8ecc2bf commit 57d5be1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 17 deletions.
23 changes: 9 additions & 14 deletions internal/denominations.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
package internal

import (
"math/big"
"fmt"
)

const (
utiaPerTia = 1_000_000 // 1 tia = 1 million utia
// utiaPerTia is the number of utia in one TIA. One tia = one million utia.
utiaPerTia = 1_000_000
// precision is the number of decimal places to show for display values of
// TIA. This level of precision ensures that the smallest unit of TIA (one
// utia) is always visible when displaying values as TIA.
precision = 6
)

// FormatTia converts utia to TIA
func FormatTia(utia int64) string {
x := newBigFloat(utia)
y := newBigFloat(utiaPerTia)
tia := new(big.Float)
tia.Quo(x, y)
tiaString := new(big.Float).SetPrec(7).SetMode(big.ToZero).Set(tia).Text('f', -1)
return tiaString
}

func newBigFloat(x int64) *big.Float {
bigFloat := new(big.Float)
bigFloat.SetInt64(x)
return bigFloat
result := float64(utia) / float64(utiaPerTia)
return fmt.Sprintf("%.*f", precision, result)
}
8 changes: 5 additions & 3 deletions internal/denominations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ func TestFormatTia(t *testing.T) {
want string
}
testCases := []testCase{
{0, "0"},
{0, "0.000000"},
{1, "0.000001"},
{utiaPerTia, "1"},
{utiaPerTia + 1, "1.000001"}, // this test case fails
{utiaPerTia, "1.000000"},
{utiaPerTia + 1, "1.000001"},
{publicAllocationGenesis, "74057350.000000"},
{initialTotalSupplyInUtia, "1000000000.000000"}, // 1 billion TIA
}
for _, tc := range testCases {
got := FormatTia(tc.utia)
Expand Down

0 comments on commit 57d5be1

Please sign in to comment.