843
i := 123
s := string(i) 

s is 'E', but what I want is "123"

Please tell me how can I get "123".

2

11 Answers 11

1280

Use the strconv package's Itoa function.

For example:

package main

import (
    "strconv"
    "fmt"
)

func main() {
    t := strconv.Itoa(123)
    fmt.Println(t)
}
Sign up to request clarification or add additional context in comments.

16 Comments

Why did the language designers think that cryptic functions names like "Itoa" were preferable to something that might be a little more descriptive?
@luke it comes from the C heritage where the entire machine might have 256K memory; usability was sacrificed to fit more functionality in. The creators of Go are all deeply embedded in that heritage and feel entirely comfortable with these names.
Putting history above accessibility and ease of learning is bad design IMO. :(
@Luke Depends on who your target users are and how strong the convention is. Some UIs still have a floppy disk as the Save icon :)
for easy remembering name ItoA - Integer to ASCII
|
217
fmt.Sprintf("%v",value);

If you know the specific type of value use the corresponding formatter for example %d for int

More info - fmt

5 Comments

I would not recommend this, as this is far less efficient than other conversion methods because it uses reflection.
But if you don't know the specific type, Sprintf is the way to go.
I heard the implementation of sprintf in c to parse a json file was the reason GTA's online mode used to take around 14 minutes to start. An Indie dev pointed it out and the load time got all the way down to ~1.5 minutes
fmt.Sprint is simpler.
@RicardoSouza I agree
107

fmt.Sprintf, strconv.Itoa and strconv.FormatInt will do the job. But Sprintf will use the package reflect, and it will allocate one more object, so it's not an efficient choice.

enter image description here

1 Comment

And strconv.FormatUint() for uint64 -> string
94

It is interesting to note that strconv.Itoa is shorthand for

func FormatInt(i int64, base int) string

with base 10

For Example:

strconv.Itoa(123)

is equivalent to

strconv.FormatInt(int64(123), 10)

1 Comment

Interesting to note that calling FormatInt() directly instead of Itoa() saves 0.1 nanosecond according to the benchmark at stackoverflow.com/a/38077508/968244
48

You can use fmt.Sprintf or strconv.FormatFloat

For example

package main

import (
    "fmt"
)

func main() {
    val := 14.7
    s := fmt.Sprintf("%f", val)
    fmt.Println(s)
}

Comments

36

In this case both strconv and fmt.Sprintf do the same job but using the strconv package's Itoa function is the best choice, because fmt.Sprintf allocate one more object during conversion.

check the nenchmark result of both check the benchmark here: https://gist.github.com/evalphobia/caee1602969a640a4530

see https://play.golang.org/p/hlaz_rMa0D for example.

3 Comments

@Boon In visible impact to your app? As always - it depends. Another object means one more object, beyond the obvious temporary small memory hit, needs to be garbage collected. If you are calling the function at high rates, for example as part of some serialization process used whenever a message is received from somewhere, it could have a significant impact. Since fmt.Sprintf and strconv.iota are similar in terms of ease of use and the above data shows iota to be faster with lower GC impact, it appears that iota should be used in general when a single integer needs converting.
Seems like premature optimization to me to be thinking at this level so soon. Best is to write readable code first.
@Boon They're equally readable. Might as well use the faster one. Also, what's to say a new Golang programmer isn't starting with something that does lots of these conversions? I'm an experienced programmer writing my first Golang code right now and am in that situation.
20

Another option:

package main
import "fmt"

func main() {
   n := 123
   s := fmt.Sprint(n)
   fmt.Println(s == "123")
}

https://golang.org/pkg/fmt#Sprint

1 Comment

Thank you very much. This is the a convenient and easy to remember solution (my point of view).
16

Converting int64:

n := int64(32)
str := strconv.FormatInt(n, 10)

fmt.Println(str)
// Prints "32"

Comments

9

ok,most of them have shown you something good. Let'me give you this:

// ToString Change arg to string
func ToString(arg interface{}, timeFormat ...string) string {
    if len(timeFormat) > 1 {
        log.SetFlags(log.Llongfile | log.LstdFlags)
        log.Println(errors.New(fmt.Sprintf("timeFormat's length should be one")))
    }
    var tmp = reflect.Indirect(reflect.ValueOf(arg)).Interface()
    switch v := tmp.(type) {
    case int:
        return strconv.Itoa(v)
    case int8:
        return strconv.FormatInt(int64(v), 10)
    case int16:
        return strconv.FormatInt(int64(v), 10)
    case int32:
        return strconv.FormatInt(int64(v), 10)
    case int64:
        return strconv.FormatInt(v, 10)
    case string:
        return v
    case float32:
        return strconv.FormatFloat(float64(v), 'f', -1, 32)
    case float64:
        return strconv.FormatFloat(v, 'f', -1, 64)
    case time.Time:
        if len(timeFormat) == 1 {
            return v.Format(timeFormat[0])
        }
        return v.Format("2006-01-02 15:04:05")
    case jsoncrack.Time:
        if len(timeFormat) == 1 {
            return v.Time().Format(timeFormat[0])
        }
        return v.Time().Format("2006-01-02 15:04:05")
    case fmt.Stringer:
        return v.String()
    case reflect.Value:
        return ToString(v.Interface(), timeFormat...)
    default:
        return ""
    }
}

2 Comments

This is great! You may include uint+uint8-64 to have a complete list
Or you could just use fmt.Sprint that does the same (except for time.Time and jsoncrack.Time (a package that will add dependencies I have never heard of) values).
4
package main

import (
    "fmt" 
    "strconv"
)

func main(){
    intValue := 123
    // keeping it in separate variable : 
    strValue := strconv.Itoa(intValue) 
    fmt.Println(strValue)
}

Comments

0

If you need to convert an int value to string, you can use faiNumber package. faiNumber is the fastest golang string parser library. All of faiNumber's function was benchmark to run way faster than the strconv package. faiNumber supports converting an int32, uint32, int64, or uint64 value to a decimal string, a binary string, an octal string, or a hex string.

You can download faiNumber from https://github.com/kevinhng86/faiNumber-Go. After download, put the faiNumber folder in your module path and import using <module_path>/faiNumber. Or you can install the faiNumber package using "go install github.com/kevinhng86/faiNumber-Go/faiNumber@latest" then using "go get github.com/kevinhng86/faiNumber-Go/faiNumber" in your module directory. If you choose to install faiNumber using go install, then you can keep the same import path.

The documentation for faiNumber can be found here https://lib.fai.host/go/github.com/kevinhng86/faiNumber-Go/faiNumber/.

I wrote faiNumber and hope that one day it will make it to the standard library.

Below is the code example for using faiNumber to convert an int32, a uint32, an int64, and a uint64 to a string of decimal.

package main
import "fmt"
import "github.com/kevinhng86/faiNumber-Go/faiNumber"

func main() {
    var nInt32 int32 = -123
    var nUint32 uint32 = 456789
    var nInt64 int64 = -123456
    var nUint64 uint64 = 9874567
    var str string

    // int32 to decimal string
    str = faiNumber.Int32ToDec(nInt32)
    fmt.Printf("int32: %d, string: %s\n", nInt32, str)

    // uint32 to decimal string
    str = faiNumber.UInt32ToDec(nUint32)
    fmt.Printf("uint32: %d, string: %s\n", nUint32, str)

    // int64 to decimal string
    str = faiNumber.Int64ToDec(nInt64)
    fmt.Printf("int64: %d, string: %s\n", nInt64, str)

    // uint64 to decimal string
    str = faiNumber.UInt64ToDec(nUint64)
    fmt.Printf("uint64: %d, string: %s\n", nUint64, str)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.