6 examples of 'convert float to int' in Go

Every line of 'convert float to int' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Go code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
78func convertToIntFloat(v float64, curMaxMult uint8) (float64, uint8, bool, error) {
79 if curMaxMult == 0 && v < maxInt {
80 // Quick check for vals that are already ints
81 i, r := math.Modf(v)
82 if r == 0 {
83 return i, 0, false, nil
84 }
85 }
86
87 if curMaxMult > maxMult {
88 return 0.0, 0, false, errInvalidMultiplier
89 }
90
91 val := v * multipliers[int(curMaxMult)]
92 sign := 1.0
93 if v < 0 {
94 sign = -1.0
95 val = val * -1.0
96 }
97
98 for mult := curMaxMult; mult <= maxMult && val < maxOptInt; mult++ {
99 i, r := math.Modf(val)
100 if r == 0 {
101 return sign * i, mult, false, nil
102 } else if r < 0.1 {
103 // Round down and check
104 if math.Nextafter(val, 0) <= i {
105 return sign * i, mult, false, nil
106 }
107 } else if r > 0.9 {
108 // Round up and check
109 next := i + 1
110 if math.Nextafter(val, next) >= next {
111 return sign * next, mult, false, nil
112 }
113 }
114 val = val * 10.0
115 }
116
117 return v, 0, true, nil
118}
68func (stdRecipes) float64ToInt32(c Converter, in float64, out *int32) error {
69 *out = int32(in)
70 return nil
71}
8func StrToFloat(val string) float64 {
9 if i, err := strconv.ParseFloat(val, 64); err == nil {
10 return i
11 }
12 return 0
13}
85func i2int(i interface{}) int {
86 switch i.(type) {
87 case string:
88 val, _ := strconv.ParseFloat(i.(string), 32)
89 return int(val)
90 case int:
91 return i.(int)
92 case float64:
93 return int(i.(float64))
94 }
95 panic(i)
96}
40func ConverFloat(str string) (float64, error) {
41 args := strings.Split(str, ".")
42 var newStr string
43 for k, v := range args {
44 if k == 0 {
45 newStr = string(v) + "."
46 } else {
47 newStr = newStr + string(v)
48 }
49 }
50 version, err := strconv.ParseFloat(newStr, 64)
51 return version, err
52}
60func IntAsFloat(i *big.Int, decimals int) *big.Float {
61 f := new(big.Float)
62 f.SetPrec(100)
63 f.SetInt(i)
64 f.Quo(f, big.NewFloat(math.Pow10(decimals)))
65 return f
66}

Related snippets