encoding.go

 1package encoding
 2
 3import (
 4	"fmt"
 5	"math"
 6	"strconv"
 7)
 8
 9// EncodeFloat encodes a float value as per the stdlib encoder for json and xml protocol
10// This encodes a float value into dst while attempting to conform to ES6 ToString for Numbers
11//
12// Based on encoding/json floatEncoder from the Go Standard Library
13// https://golang.org/src/encoding/json/encode.go
14func 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		// clean up e-09 to e-9
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}