Help us shape the future of Go! Take the 2026 Go Developer Survey

marshaljsonf64

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 6, 2020 License: MIT Imports: 6 Imported by: 0

README

marshaljsonf64

なぜこれを作ったか

type Hoge struct {
	Foo float32
	Bar float64
}

func main() {
	hoge := Hoge{Foo: 2415919104, Bar: 2415919104}
	j, _ := json.Marshal(hoge)
	fmt.Printf("Foo=%.0f, Bar=%.0f\n", hoge.Foo, hoge.Bar)
	//=> Foo=2415919104, Bar=2415919104

	fmt.Println(string(j))
	//=> {"Foo":2415919000,"Bar":2415919104}
}

hoge.Foo は 2415919104 なのに、 json にしたときは 2415919000 に丸められてしまう。 困る。

使い方

package main

import (
	"encoding/json"
	"fmt"
	"reflect"

	"github.com/nabetani/marshaljsonf64"
)

type banana struct {
	Foo float32
}

type cherry struct {
	Foo float32
}

// MarshalJSON この関数を実装すると json.Marshal 内で呼ばれる
func (o cherry) MarshalJSON() ([]byte, error) {
	return marshaljsonf64.Impl(&o, reflect.TypeOf(o))
}

func main() {
	b := banana{Foo: 2415919104}
	c := cherry{Foo: 2415919104}
	jb, _ := json.Marshal(b)
	jc, _ := json.Marshal(c)
	fmt.Println("banana:", string(jb))
	//=> banana: {"Foo":2415919000}
	
	fmt.Println("cherry:", string(jc))
	//=> cherry: {"Foo":2415919104}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Impl

func Impl(o interface{}, t reflect.Type) ([]byte, error)

Impl メンバに float32 型の値がある場合に、 精度多めで出力するためのメソッド

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL