golang如何移除字符串中的”%!d(string=”部分。

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

golang how to remove %!d(string= in string

问题

我有这样的代码:

newStr := fmt.Sprintf("new price: %d€", newPrice)
fmt.Println(newStr) // new price:  %!d(string=500.00)€
// 但我想要的是:new price: 500,00€

如何去掉字符串末尾的 %!d(),使其变成 new price: 500,00€

我可以使用 strings.Replace 来格式化,但我不认为这是正确的答案。

我的 newPrice 是一个浮点数。

我相信这个问题已经被问过了,但是很难在谷歌上找到这些东西。

英文:

I have this:

newStr := fmt.Sprintf("new price: %d", newPrice)
fmt.Println(newStr) // new price:  %!d(string=500.00)€
// except I want: new price: 500,00€

How to remove the %!d( and the ) at the end of the string so it can be like this new price: 500,00€

I could use a format the strings.Replace but I don't think it's the good answer.

My newPrice is a float.

I'm pretty sure it as already been ask but it's hard to google those kind of things.

答案1

得分: 6

问题在于你在调用fmt.Sprintf()时,使用了%d来表示整数值,但实际传递的是一个浮点数值(500.00)。

尝试使用以下代码:

newStr := fmt.Sprintf("新价格:%f€", newPrice)
fmt.Println(newStr)

这样应该可以解决问题。

英文:

The problem is that you're using %d for an integer value in your call to fmt.Sprintf(), but passing a floating-point value (500,00).

Try this:

newStr := fmt.Sprintf("new price: %f€", newPrice)
fmt.Println(newStr) 

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

发表评论

匿名网友

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

确定