-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfloat.go
40 lines (33 loc) · 848 Bytes
/
float.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package g
import (
"errors"
"fmt"
"strconv"
)
// StringToFloat converts a string to a float.
// If the conversion fails and a default value is provided, it
// returns the default value. Otherwise, it returns an error.
//
// Example Usage:
//
// f, err := StringToFloat("3.14") // 3.14, nil
// f, err := StringToFloat("abc", 1.23) // 1.23, error
func StringToFloat(v string, def ...float64) (float64, error) {
var d float64 = 0
if len(def) > 0 {
d = def[0]
}
if v == "" {
return d, errors.New("empty string and no default value")
}
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return d, err
}
return f, nil
}
// FloatToString converts a float to a string.
// It handles different floating-point types such as float32 and float64.
func FloatToString[T ~float32 | ~float64](v T) string {
return fmt.Sprintf("%v", v)
}