zyc
zyc

Reputation: 447

What's the best way to convert an Int to a String in Julia?

I am using Julia (version 0.4.6), and the method that I have tried is:

a = 123 
println(  string(Int(a))*"b"  )

Which looks long and awkward.

The other way I have tried is to write it to a file, and then read it. This is clearly worse. I wonder if there is a recommended method.

Upvotes: 3

Views: 1883

Answers (1)

Michael Ohlrogge
Michael Ohlrogge

Reputation: 10990

I'm not sure what you're trying to accomplish with the *"b" in your syntax, but for the rest of it:

julia> a = 123
123

julia> string(a)
"123"

julia> println(a)
123

The string() function can also take more arguments:

julia> string(a, "b")
"123b"

Note that it is not necessary to convert an Int type to an ASCIIString before calling println() on it - the conversion will occur automatically.

You can also insert (aka interpolate) integers (and certain other types) into strings using $:

julia> MyString = "my integer is $a"
"my integer is 123"

Performance Tip: The above methods can be quite convenient at times. But, if you will be performing many, many such operations and you are concerned about execution speed of your code, the Julia performance guide recommends against this, and instead in favor of the below methods:

You can supply multiple arguments to print() and println() which will operate on them exactly as string() operates on multiple arguments:

julia> println(a, "b")
123b

Or, when writing to file, you can similarly use, e.g.

open("/path/to/MyFile.txt", "w") do file
    println(file, a, "b", 13)
end

or

file = open("/path/to/MyFile.txt", "a")
println(file, a, "b", 13)
close(file)

These are faster because they avoid needing to first form a string from given pieces and then output it (either to the console display or a file) and instead just sequentially output the various pieces.

Note: Answer reflects updates based on helpful comment from @Fengyang Wang.

Upvotes: 9

Related Questions