concatenating a string and a float

3,351 views
Skip to first unread message

chinmay

unread,
Jul 1, 2011, 12:17:16 PM7/1/11
to golang-nuts
Hi all,

Please tell me how do I concatenate a string and a float
Generally how do I convert a float (or any other type) to string
format ?

eaburns

unread,
Jul 1, 2011, 12:24:43 PM7/1/11
to golan...@googlegroups.com
This seemed to work for me:

package main

import "fmt"

func main() {
str := "pi: " + fmt.Sprintf("%g", 3.1415926536)
fmt.Printf("%s\n", str)
}

eaburns

unread,
Jul 1, 2011, 12:28:14 PM7/1/11
to golan...@googlegroups.com
By the way, I explicitly tried to separate the conversion and the concatenation.  Obviously you can probably easily find a much simpler program that accomplishes the same thing :-D

chinmay

unread,
Jul 1, 2011, 12:29:59 PM7/1/11
to golang-nuts
okay,
after reading the docs I feel Ftoa32 is a better method !

Steven Blenkinsop

unread,
Jul 1, 2011, 12:30:56 PM7/1/11
to golan...@googlegroups.com

You could also do:
str := fmt.Sprintf("%s: %g", "pi", 3.1415926536)

Or whatever floats your boat.

chris dollin

unread,
Jul 1, 2011, 12:51:59 PM7/1/11
to chinmay, golang-nuts

Have I not already mentioned the fmt package? If so, I'll
mention it again: the fmt package.

Chris

--
Chris "allusive" Dollin

Leandro Loriato

unread,
Jul 1, 2011, 12:59:57 PM7/1/11
to golang-nuts
Isn't the strconv package made just for this kind of stuff?

--
"The reasonable man adapts himself to the
world; the unreasonable persists in trying
to adapt the world to himself. Therefore
all progress depends on the unreasonable." - George Bernard Shaw

chris dollin

unread,
Jul 1, 2011, 1:16:32 PM7/1/11
to Leandro Loriato, golang-nuts
On 1 July 2011 17:59, Leandro Loriato <leandro...@gmail.com> wrote:
> Isn't the strconv package made just for this kind of stuff?

Some of it (but a good point despite my following):

... conversions to and from string representations of basic data types.

So if you have maps and slices and structs and stuff, you'd have
to write a deal by hand. Depending on /exactly/ what one is trying
to do -- the OP isn't specific -- one or other may be more useful.

barnex

unread,
Jul 1, 2011, 1:45:41 PM7/1/11
to golang-nuts
I prefer:

fmt.Sprint("pi:", 3.1415926536)

-Arne
Reply all
Reply to author
Forward
0 new messages