Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした