-
Notifications
You must be signed in to change notification settings - Fork 2
/
streamer_float.go
87 lines (84 loc) · 1.46 KB
/
streamer_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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package jzon
import (
"math"
"strconv"
)
// Float32 writes a float32 value
func (s *Streamer) Float32(f float32) *Streamer {
if s.Error != nil {
return s
}
f64 := float64(f)
if math.IsInf(f64, 0) {
s.Error = ErrFloatIsInfinity
return s
}
if math.IsNaN(f64) {
s.Error = ErrFloatIsNan
return s
}
s.onVal()
fmt := byte('f')
abs := math.Abs(f64)
if abs != 0 {
if f > 0 {
if f < 1e-6 || f >= 1e21 {
fmt = 'e'
}
} else {
if f > -1e-6 || f <= -1e21 {
fmt = 'e'
}
}
}
s.buffer = strconv.AppendFloat(s.buffer, f64, fmt, -1, 32)
if fmt == 'e' {
n := len(s.buffer)
if n > 4 && s.buffer[n-4] == 'e' &&
s.buffer[n-3] == '-' &&
s.buffer[n-2] == '0' {
s.buffer[n-2] = s.buffer[n-1]
s.buffer = s.buffer[:n-1]
}
}
return s
}
// Float64 writes a float64 value
func (s *Streamer) Float64(f float64) *Streamer {
if s.Error != nil {
return s
}
if math.IsInf(f, 0) {
s.Error = ErrFloatIsInfinity
return s
}
if math.IsNaN(f) {
s.Error = ErrFloatIsNan
return s
}
s.onVal()
fmt := byte('f')
abs := math.Abs(f)
if abs != 0 {
if f > 0 {
if f < 1e-6 || f >= 1e21 {
fmt = 'e'
}
} else {
if f > -1e-6 || f <= -1e21 {
fmt = 'e'
}
}
}
s.buffer = strconv.AppendFloat(s.buffer, f, fmt, -1, 64)
if fmt == 'e' {
n := len(s.buffer)
if n > 4 && s.buffer[n-4] == 'e' &&
s.buffer[n-3] == '-' &&
s.buffer[n-2] == '0' {
s.buffer[n-2] = s.buffer[n-1]
s.buffer = s.buffer[:n-1]
}
}
return s
}