How to convert number (int or float64) to string in Golang

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

How to convert number (int or float64) to string in Golang

问题

如何将任意给定的数字(可以是int或float64类型)转换为字符串?

使用strconv.FormatFloat或FormatInt函数,您需要指定给定数字是浮点数还是整数。
在我的情况下,我不知道我得到的是什么类型的数字。

行为:

当我得到一个5时,它应该被转换为"5"而不是"5.00"

当我得到一个1.23时,它应该被转换为"1.23"而不是"1"

英文:

How do I convert any given number which can be a int or float64 to string ?

Using strconv.FormatFloat or FormatInt I have to specify that the given number is a float or integer.
In my case it is unknown what I get.

Behaviour:

When I get a 5 it should be converted into "5" and not "5.00"

When I get a 1.23 it should be converted into "1.23" and not "1"

答案1

得分: 17

你可以使用fmt.Sprint

fmt.Sprint将传递给它的任何变量转换为字符串格式。

示例

package main

import (
	"fmt"
)

func main() {
    f := fmt.Sprint(5.03)
    i := fmt.Sprint(5)
	fmt.Println("float:", f, "\nint:", i)
}

play链接

英文:

You may use fmt.Sprint

fmt.Sprint returns string format of any variable passed to it

Sample

package main

import (
	"fmt"
)

func main() {
    f := fmt.Sprint(5.03)
    i := fmt.Sprint(5)
	fmt.Println("float:",f,"\nint:",i)
}

play link

答案2

得分: 2

如果你不知道需要转换为字符串的数字的类型,你可以使用fmt.Sprintf%v占位符:

fmt.Sprintf("%v", 1.23) // "1.23"
fmt.Sprintf("%v", 5) // "5"
英文:

If you don't know what type the number you need to convert to string will be, you can just use fmt.Sprintf with the %v verb:

fmt.Sprintf("%v", 1.23) // "1.23"
fmt.Sprintf("%v", 5) // "5"

huangapple
  • 本文由 发表于 2017年6月14日 16:45:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/44539789.html
匿名

发表评论

匿名网友

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

确定