Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions float16.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions float16_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
14 changes: 14 additions & 0 deletions float16_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down