LoginSignup
0
2

More than 1 year has passed since last update.

【Golang】文字列と数値の変換(strconv)

Posted at

Goの勉強中にstring型の型変換で少し詰まったので、調べてわかったことを簡単に紹介します。

strconv パッケージ

文字列を数値に変換したいときは、strconvパッケージを使用します。この記事では、文字列と数値の変換しか紹介していませんが、bool型との変換なども存在します。また、違ったやり方もあるので、もっと詳しく知りたい方は公式ドキュメント(strconv)を読んでみてください。

string <-> intの変換

  • strconv.Atoi(s string): string型 -> int型
    引数で指定された文字列を数値(int型)に変換して返します。
    また、2番目の返り値としてerror型を返します。

  • strconv.Itoa(i int): int型 -> string型
    引数で指定された数値(int型)を文字列に変換して返します。

Atoi関数は、2番目の返り値としてerror型を返しますが、今回はエラー処理を省略するため使用しません。Atoi関数ではint型に変換されるため、数値の加算ができています。一方で、Itoa関数ではstring型に変換されるため、s1とs2が連結されています。

main.go
package main

import (
	"fmt"
	"strconv"
)

func main() {
	a, _ := strconv.Atoi("7")
	b, _ := strconv.Atoi("-3")
	fmt.Printf("a_type:%T\n", a) // => a_type:int
	fmt.Printf("b_type:%T\n", b) // => b_type:int
	fmt.Println(a + b)           // => 4

	s1 := strconv.Itoa(7)
	s2 := strconv.Itoa(-3)
	fmt.Printf("s1_type:%T\n", s1) // => s1_type:int
	fmt.Printf("s2_type:%T\n", s2) // => s2_type:int
	fmt.Println(s1 + s2)           // => 7-3
}

string -> floatの変換

  • strconv.ParseFloat(s string, bitSize int): string型 -> float型
    引数で指定された文字列を数値(float型)に変換して返します。
    2番目の引数 bitSize で精度を指定します。float32の場合は32、float64の場合は64と指定します。
    2番目の返り値としてerror型を返します。
main.go
	a_f64, _ := strconv.ParseFloat("3.14", 64)
	b_f64, _ := strconv.ParseFloat("-1.41", 64)
	fmt.Printf("a_f64_type:%T\n", a_f64) // => a_f64_type:float64
	fmt.Printf("b_f64_type:%T\n", b_f64) // => b_f64_type:float64
	fmt.Printf("%.2f\n", a_f64 + b_f64)    // => 1.73

終わりに

冒頭でもお伝えしましたが、float型 -> string型の変換などここでは紹介していない変換もあるので、詳しくは公式ドキュメント(strconv)を読んでみてください。

0
2
0

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
0
2