めんどくさいので探した。
Arggh Golang does not include a round function in the standard math package. So I wrote a quick one.
ここにあるround.goを実行すると、
2015/02/19 19:30:33 123.556 2015/02/19 19:30:33 123.56
のように出る。 ログを使ってるので日付が出るが・・・
要は、
> Round(123.555555, .5, 3) 123.556
> Round(123.558, .5, 2) 123.56
「.5」は四捨五入のために入れてるようだ。 第3引数の位置で丸める。
わざわざ「.5」を入れるのは面倒なので、 この返信に有る
func Round(f float64) float64 { return math.Floor(f + .5) } func RoundPlus(f float64, places int) (float64) { shift := math.Pow(10, float64(places)) return Round(f * shift) / shift; }
の方が便利。
import "math"
忘れずに。
でもさすがに2つメソッドは手間なので、、
func Round(f float64, places int) (float64) { shift := math.Pow(10, float64(places)) return math.Floor(f * shift + .5) / shift }
で1メソッドでOK。
出力は
> fmt.Printf("%.2f\n", Round(0.1214, 2)) 0.12
「%.2f」のようにした。 そうしないと、小数点とがが無駄に出る。