github.com/MetalBlockchain/metalgo@v1.11.9/utils/json/float64.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package json 5 6 import "strconv" 7 8 type Float64 float64 9 10 func (f Float64) MarshalJSON() ([]byte, error) { 11 return []byte(`"` + strconv.FormatFloat(float64(f), byte('f'), 4, 64) + `"`), nil 12 } 13 14 func (f *Float64) UnmarshalJSON(b []byte) error { 15 str := string(b) 16 if str == Null { 17 return nil 18 } 19 if len(str) >= 2 { 20 if lastIndex := len(str) - 1; str[0] == '"' && str[lastIndex] == '"' { 21 str = str[1:lastIndex] 22 } 23 } 24 val, err := strconv.ParseFloat(str, 64) 25 *f = Float64(val) 26 return err 27 }