0
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 1 year has passed since last update.

0埋めの文字列にする

Posted at

やったこと

go言語で0埋めの関数なかったのでつくっった。
テストコードとか書いてないので確実に動くかはわかんないけど多分大丈夫(適当)

package main

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/labstack/gommon/log"
)

func main() {
	n := 1000
	width := 3
	var s string
	s, err := padNumberWithZeros(n, width)
	if err != nil {
		log.Error("err : ", err)
		return
	}

	fmt.Println(s)
}

// padNumberWithZeros : 数理をセロで埋めます
//    n : 埋めたい数値
//    width : 桁数
func padNumberWithZeros(n int, width int) (s string, err error) {
	l := len(strconv.Itoa(n))
	if l > width {
		return "", errors.New("overflow")
	}
	padded := "%0" + strconv.Itoa(width) + "d"
	s = fmt.Sprintf(padded, n%100)

	// success
	return s, nil
}
0
0
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
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?