4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go言語のfmtパッケージは小数点以下を切り捨てない

Last updated at Posted at 2018-04-19

Goのfmtパッケージには書式演算子があります
https://godoc.org/fmt

浮動小数点数型のfloat64を、小数点以下第n位で切り捨てたい場合には
書式演算子 %f を使って文字列型に一度変換して、浮動小数点数型に変換する方法が楽かと思います

ですが、 %f は指定した有効桁数で小数点以下を切り捨ててくれないので、この方法は使えません

サンプルコード

package main

import (
	"fmt"
)

func main() {
	// 小数点以下第3位で切り捨てられることを期待
	s := fmt.Sprintf("%.3f", 0.0019)
	fmt.Println("%s", s)
}

実行結果

%s 0.002

四捨五入されます
参考: https://play.golang.org/p/C5AP_7V3wd9

代替案

小数点数以下第n位を有効桁数として切り捨てたいときは、 math パッケージの PowFloor メソッドを使って実装するのがよいかと思います
https://godoc.org/math#Floor

参考: https://gist.github.com/DavidVaini/10308388

4
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?