encoding.go 983 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package encoding
  2. import (
  3. "fmt"
  4. "math"
  5. "strconv"
  6. )
  7. // EncodeFloat encodes a float value as per the stdlib encoder for json and xml protocol
  8. // This encodes a float value into dst while attempting to conform to ES6 ToString for Numbers
  9. //
  10. // Based on encoding/json floatEncoder from the Go Standard Library
  11. // https://golang.org/src/encoding/json/encode.go
  12. func EncodeFloat(dst []byte, v float64, bits int) []byte {
  13. if math.IsInf(v, 0) || math.IsNaN(v) {
  14. panic(fmt.Sprintf("invalid float value: %s", strconv.FormatFloat(v, 'g', -1, bits)))
  15. }
  16. abs := math.Abs(v)
  17. fmt := byte('f')
  18. if abs != 0 {
  19. if bits == 64 && (abs < 1e-6 || abs >= 1e21) || bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) {
  20. fmt = 'e'
  21. }
  22. }
  23. dst = strconv.AppendFloat(dst, v, fmt, -1, bits)
  24. if fmt == 'e' {
  25. // clean up e-09 to e-9
  26. n := len(dst)
  27. if n >= 4 && dst[n-4] == 'e' && dst[n-3] == '-' && dst[n-2] == '0' {
  28. dst[n-2] = dst[n-1]
  29. dst = dst[:n-1]
  30. }
  31. }
  32. return dst
  33. }