diff --git a/float16.go b/float16.go index c315091..e751e54 100644 --- a/float16.go +++ b/float16.go @@ -222,6 +222,11 @@ func (f Float16) String() string { return strconv.FormatFloat(float64(f.Float32()), 'f', -1, 32) } +// MarshalJSON satisfies json marshaller +func (f Float16) MarshalJSON() ([]byte, error) { + return []byte(f.String()), nil +} + // f16bitsToF32bits returns uint32 (float32 bits) converted from specified uint16. func f16bitsToF32bits(in uint16) uint32 { // All 65536 conversions with this were confirmed to be correct diff --git a/float16_bench_test.go b/float16_bench_test.go index bd9fbfa..28c08b2 100644 --- a/float16_bench_test.go +++ b/float16_bench_test.go @@ -86,3 +86,15 @@ func BenchmarkString(b *testing.B) { } resultStr = result } + +func BenchmarkMarshalJson(b *testing.B) { + var result []byte + + pi32 := float32(math.Pi) + pi16 := float16.Fromfloat32(pi32) + + for i := 0; i < b.N; i++ { + result, _ = pi16.MarshalJSON() + } + resultStr = string(result) +} diff --git a/float16_test.go b/float16_test.go index 104a8de..6b1a614 100644 --- a/float16_test.go +++ b/float16_test.go @@ -616,6 +616,20 @@ func TestString(t *testing.T) { } +func TestMarshalJson(t *testing.T) { + f16 := float16.Fromfloat32(1.5) + s, _ := f16.MarshalJSON() + if string(s) != "1.5" { + t.Errorf("Float16(1.5).MarshalJson() returned %s, wanted 1.5", s) + } + + f16 = float16.Fromfloat32(3.14159) + s, _ = f16.MarshalJSON() + if string(s) != "3.140625" { + t.Errorf("Float16(3.141593).MarshalJson() returned %s, wanted 3.140625", s) + } +} + func TestIsInf(t *testing.T) { f16 := float16.Float16(0)