jsoniter_float_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package jsoniter
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "testing"
  6. "github.com/json-iterator/go/require"
  7. "bytes"
  8. "strconv"
  9. )
  10. func Test_float64_0(t *testing.T) {
  11. iter := ParseString(`0`)
  12. val := iter.ReadFloat64()
  13. if val != 0 {
  14. t.Fatal(val)
  15. }
  16. }
  17. func Test_float64_1_dot_1(t *testing.T) {
  18. iter := ParseString(`1.1`)
  19. val := iter.ReadFloat64()
  20. if val != 1.1 {
  21. t.Fatal(val)
  22. }
  23. }
  24. func Test_float32_1_dot_1_comma(t *testing.T) {
  25. iter := ParseString(`1.1,`)
  26. val := iter.ReadFloat32()
  27. if val != 1.1 {
  28. fmt.Println(iter.Error)
  29. t.Fatal(val)
  30. }
  31. }
  32. func Test_write_float32(t *testing.T) {
  33. vals := []float32{0, 1, -1, 99, 0xff, 0xfff, 0xffff, 0xfffff, 0xffffff, 0x4ffffff, 0xfffffff,
  34. -0x4ffffff, -0xfffffff, 1.2345, 1.23456, 1.234567, 1.001}
  35. for _, val := range vals {
  36. t.Run(fmt.Sprintf("%v", val), func(t *testing.T) {
  37. should := require.New(t)
  38. buf := &bytes.Buffer{}
  39. stream := NewStream(buf, 4096)
  40. stream.WriteFloat32(val)
  41. stream.Flush()
  42. should.Nil(stream.Error)
  43. should.Equal(strconv.FormatFloat(float64(val), 'f', -1, 32), buf.String())
  44. })
  45. }
  46. should := require.New(t)
  47. buf := &bytes.Buffer{}
  48. stream := NewStream(buf, 10)
  49. stream.WriteRaw("abcdefg")
  50. stream.WriteFloat32(1.123456)
  51. stream.Flush()
  52. should.Nil(stream.Error)
  53. should.Equal("abcdefg1.123456", buf.String())
  54. }
  55. func Benchmark_jsoniter_float(b *testing.B) {
  56. b.ReportAllocs()
  57. for n := 0; n < b.N; n++ {
  58. iter := ParseString(`1.1111111111`)
  59. iter.ReadFloat64()
  60. }
  61. }
  62. func Benchmark_json_float(b *testing.B) {
  63. for n := 0; n < b.N; n++ {
  64. result := float64(0)
  65. json.Unmarshal([]byte(`1.1`), &result)
  66. }
  67. }