forked from sonirico/go-hyperliquid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.go
More file actions
63 lines (52 loc) · 1.36 KB
/
utils.go
File metadata and controls
63 lines (52 loc) · 1.36 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package hyperliquid
import (
"fmt"
"math"
"strconv"
"strings"
)
// roundToDecimals rounds a float64 to the specified number of decimals.
func roundToDecimals(value float64, decimals int) float64 {
pow := math.Pow(10, float64(decimals))
return math.Round(value*pow) / pow
}
// parseFloat parses a string to float64, returns 0.0 if parsing fails.
func parseFloat(s string) float64 {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0.0
}
return f
}
// abs returns the absolute value of a float64.
func abs(x float64) float64 {
if x < 0 {
return -x
}
return x
}
// formatFloat formats a float64 to string with 6 decimal places.
func formatFloat(f float64) string {
return fmt.Sprintf("%.6f", f)
}
// floatToWire converts a float64 to a wire-compatible string format
func floatToWire(x float64) (string, error) {
// Format to 8 decimal places
rounded := fmt.Sprintf("%.8f", x)
// Check if rounding causes significant error
parsed, err := strconv.ParseFloat(rounded, 64)
if err != nil {
return "", err
}
if math.Abs(parsed-x) >= 1e-12 {
return "", fmt.Errorf("float_to_wire causes rounding: %f", x)
}
// Handle -0 case
if rounded == "-0.00000000" {
rounded = "0.00000000"
}
// Remove trailing zeros and decimal point if not needed
result := strings.TrimRight(rounded, "0")
result = strings.TrimRight(result, ".")
return result, nil
}