...
1 package encoding
2
3 import (
4 "fmt"
5 "math"
6 "strconv"
7 )
8
9
10
11
12
13
14 func EncodeFloat(dst []byte, v float64, bits int) []byte {
15 if math.IsInf(v, 0) || math.IsNaN(v) {
16 panic(fmt.Sprintf("invalid float value: %s", strconv.FormatFloat(v, 'g', -1, bits)))
17 }
18
19 abs := math.Abs(v)
20 fmt := byte('f')
21
22 if abs != 0 {
23 if bits == 64 && (abs < 1e-6 || abs >= 1e21) || bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) {
24 fmt = 'e'
25 }
26 }
27
28 dst = strconv.AppendFloat(dst, v, fmt, -1, bits)
29
30 if fmt == 'e' {
31
32 n := len(dst)
33 if n >= 4 && dst[n-4] == 'e' && dst[n-3] == '-' && dst[n-2] == '0' {
34 dst[n-2] = dst[n-1]
35 dst = dst[:n-1]
36 }
37 }
38
39 return dst
40 }
41
View as plain text