在右侧补零的情况下使用sprintf函数

huangapple go评论69阅读模式
英文:

sprintf zero pad on right side

问题

如何在右侧进行零填充?这段代码是在左侧进行零填充的。

package main

import "fmt"

func main() {
    s := fmt.Sprintf("%-06s", "45")
    fmt.Println(s)
}

输出结果:

000045

我想要的结果是:

450000
英文:

How to zero pad on the right side? This code zero pad to the left

package main

import "fmt"

func main() {
	s := fmt.Sprintf("%06s", "45")
	fmt.Println(s)
}

Output

000045

What I want

450000

答案1

得分: 2

你可以使用fmt.Sprintf("%-6s", "45")在右侧进行空格填充。

你必须自己进行填充,使用0进行填充:

// 右侧零填充
func zpadr(s string, n int) string {
n -= len(s)
if n > 0 {
s += strings.Repeat("0", n)
}
return s
}

使用方法如下:fmt.Sprintf("%s", zpadr("45", 6))

英文:

You can space pad on the right with fmt.Sprintf("%-6s", "45")

You must do your own padding to pad with 0:

// Zero PAD Right
func zpadr(s string, n int) string {
	n -= len(s)
	if n > 0 {
		s += strings.Repeat("0", n)
	}
	return s
}

Use like this: fmt.Sprintf("%s", zpadr("45", 6))

huangapple
  • 本文由 发表于 2022年10月13日 09:14:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/74049487.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定