github.com/zerosnake0/jzon@v0.0.9-0.20230801092939-1b135cb83f7f/streamer_float.go (about) 1 package jzon 2 3 import ( 4 "math" 5 "strconv" 6 ) 7 8 // Float32 writes a float32 value 9 func (s *Streamer) Float32(f float32) *Streamer { 10 if s.Error != nil { 11 return s 12 } 13 f64 := float64(f) 14 if math.IsInf(f64, 0) { 15 s.Error = ErrFloatIsInfinity 16 return s 17 } 18 if math.IsNaN(f64) { 19 s.Error = ErrFloatIsNan 20 return s 21 } 22 s.onVal() 23 fmt := byte('f') 24 abs := math.Abs(f64) 25 if abs != 0 { 26 if f > 0 { 27 if f < 1e-6 || f >= 1e21 { 28 fmt = 'e' 29 } 30 } else { 31 if f > -1e-6 || f <= -1e21 { 32 fmt = 'e' 33 } 34 } 35 } 36 s.buffer = strconv.AppendFloat(s.buffer, f64, fmt, -1, 32) 37 if fmt == 'e' { 38 n := len(s.buffer) 39 if n > 4 && s.buffer[n-4] == 'e' && 40 s.buffer[n-3] == '-' && 41 s.buffer[n-2] == '0' { 42 s.buffer[n-2] = s.buffer[n-1] 43 s.buffer = s.buffer[:n-1] 44 } 45 } 46 return s 47 } 48 49 // Float64 writes a float64 value 50 func (s *Streamer) Float64(f float64) *Streamer { 51 if s.Error != nil { 52 return s 53 } 54 if math.IsInf(f, 0) { 55 s.Error = ErrFloatIsInfinity 56 return s 57 } 58 if math.IsNaN(f) { 59 s.Error = ErrFloatIsNan 60 return s 61 } 62 s.onVal() 63 fmt := byte('f') 64 abs := math.Abs(f) 65 if abs != 0 { 66 if f > 0 { 67 if f < 1e-6 || f >= 1e21 { 68 fmt = 'e' 69 } 70 } else { 71 if f > -1e-6 || f <= -1e21 { 72 fmt = 'e' 73 } 74 } 75 } 76 s.buffer = strconv.AppendFloat(s.buffer, f, fmt, -1, 64) 77 if fmt == 'e' { 78 n := len(s.buffer) 79 if n > 4 && s.buffer[n-4] == 'e' && 80 s.buffer[n-3] == '-' && 81 s.buffer[n-2] == '0' { 82 s.buffer[n-2] = s.buffer[n-1] 83 s.buffer = s.buffer[:n-1] 84 } 85 } 86 return s 87 }