如何使用前导0和至少3位小数格式化数字?

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

How do I format numbers with a leading 0 and at least 3 decimals?

问题

假设我有一系列数字,如下所示:

"1.01","1.2345","321.1" 等等

我希望它们呈现为:

"01.010"
"01.2345"
"321.100"

所以有2位整数和3位小数,但如果超过了这个限制,也可以显示全部。

我查看了 fmt 命令的选项,但没有找到清晰地覆盖最小数字位数的内容。

这只是为了显示,所以最终结果可以是数字或字符串都可以。

英文:

Let's say I have a series of numbers like:

"1.01", "1.2345", "321.1" etc.

I want them to present as:

"01.010"
"01.2345"
"321.100"

So 2 int digits and 3 float digits, but if they exceed it fine, show them all.

I looked at the fmt command options, but didn't see anything that covers minimum number of digits cleanly.

This is just for display, so number or string is fine as an end result.

答案1

得分: 3

格式化浮点数

这是使用 f 格式化符号,精度为 3,宽度为 2+3+1 = 6(2 位小数,3 位小数部分和 1 位小数点),使用 0 前缀填充零,所以可以简单地打印如下:

fmt.Printf("%06.3f\n", f)

测试代码如下:

fs := []float64{1.01, 1.2345, 321.1}
for _, f := range fs {
    fmt.Printf("%06.3f\n", f)
}

运行结果如下(可以在 Go Playground 上尝试):

01.010
01.234
321.100

如果你想要将结果作为字符串(而不是打印到控制台),可以使用 fmt.Sprintf()

s := fmt.Sprintf("%06.3f\n", f)

注意: %06.3f 会将小数部分限制为 3 位,结果为 01.234 而不是 01.2345。这不是你要求的,但我建议限制小数位数,否则会得到意外的结果,例如:

i := 0.1
fmt.Println(i + 0.2)

运行结果如下:

0.30000000000000004

但是如果你使用:

fmt.Printf("%06.3f\n", i+0.2)

你将得到如下结果(可以在 Go Playground 上尝试):

00.300

相关问题:

https://stackoverflow.com/questions/36515818/is-there-any-standard-library-to-convert-float64-to-string-with-fix-width-with-m/36518167#36518167

https://stackoverflow.com/questions/39544571/golang-round-to-nearest-0-05/39544897#39544897

格式化字符串

标准库中没有现成的函数,所以你需要自己编写。

下面是一个简单的解决方案(不是最快的):

func format(s string) string {
    parts := strings.Split(s, ".")

    // 在左侧填充整数部分
    for len(parts[0]) < 2 {
        parts[0] = "0" + parts[0]
    }

    // 在右侧填充小数部分
    if len(parts) < 2 {
        parts = append(parts, "0")
    }
    for len(parts[1]) < 3 {
        parts[1] += "0"
    }

    return strings.Join(parts, ".")
}

测试代码如下:

nums := []string{"1.01", "1.2345", "321.1", "2", ".4"}
for _, n := range nums {
    fmt.Println(format(n))
}

输出结果如下(可以在 Go Playground 上尝试):

01.010
01.2345
321.100
02.000
00.400
英文:

Formatting floats

This is simply the f verb with 3 precision, and width being 2+3+1 = 6 width (2 decimal, 3 fractional and 1 for dot), prefix it with 0 to pad with zeros, so simply print them as:

fmt.Printf(&quot;%06.3f\n&quot;, f)

Testing it:

fs := []float64{1.01, 1.2345, 321.1}
for _, f := range fs {
	fmt.Printf(&quot;%06.3f\n&quot;, f)
}

This will output (try it on the Go Playground):

01.010
01.234
321.100

If you want the result as a string (and not print it on your console), use fmt.Sprintf():

s := fmt.Sprintf(&quot;%06.3f\n&quot;, f)

Note: %06.3f will limit fractional digits to 3, and result in 01.234 instead of 01.2345. This isn't what you asked for, but I recommend to limit the fractional digits, else you get unexpected results, for example:

i := 0.1
fmt.Println(i + 0.2)

This will output:

0.30000000000000004

But if you use

fmt.Printf(&quot;%06.3f\n&quot;, i+0.2)

You will get (try it on the Go Playground):

00.300

See related questions:

https://stackoverflow.com/questions/36515818/is-there-any-standard-library-to-convert-float64-to-string-with-fix-width-with-m/36518167#36518167

https://stackoverflow.com/questions/39544571/golang-round-to-nearest-0-05/39544897#39544897

Formatting strings

There is no ready function in the standard lib, so you have to write it yourself.

Here's a simple solution (not the fastest):

func format(s string) string {
	parts := strings.Split(s, &quot;.&quot;)

	// Pad integer part on the left
	for len(parts[0]) &lt; 2 {
		parts[0] = &quot;0&quot; + parts[0]
	}

	// Pad fractional part on the right
	if len(parts) &lt; 2 {
		parts = append(parts, &quot;0&quot;)
	}
	for len(parts[1]) &lt; 3 {
		parts[1] += &quot;0&quot;
	}

	return strings.Join(parts, &quot;.&quot;)
}

Testing it:

nums := []string{&quot;1.01&quot;, &quot;1.2345&quot;, &quot;321.1&quot;, &quot;2&quot;, &quot;.4&quot;}
for _, n := range nums {
	fmt.Println(format(n))
}

Output (try it on the Go Playground):

01.010
01.2345
321.100
02.000
00.400

huangapple
  • 本文由 发表于 2022年6月3日 01:54:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/72480417.html
匿名

发表评论

匿名网友

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

确定