While coding, we often need to convert the type of data members. In this Answer, we'll learn to convert a string to a number in Julia. Following are a few ways to convert a string to a number:
Convert the string to an integer number.
Convert the string to a float number.
Convert the string to an integer with the given base.
To convert a string to a number, we can use the parse()
function. The syntax of this function is as follows:
parse(type, str, base)
Here are the details of this function's parameters:
type
: This is the data type we want to convert the string to.
str
: This is the string we want to convert.
base
: This is the base to which the string is to be converted. It is an optional parameter, and it should be a positive integer.
Let's move ahead and see how to use this function in the Julia code.
Following is an example of converting a string to an integer number. Click the "Run" button below to see the output:
str = readline()println("Following is the ", typeof(str), ": ", str)num = parse(Int64, str)println("Following is in ", typeof(num), ": ", num)
Enter the input below
Here is the explanation of the code:
Line 1: We read a string from the "Enter the input below" box.
Line 2: We print the given string and its type using the typeof(str)
function.
Line 3: We convert it to an integer.
Line 4: We print the integer resulting from the given string and its type.
Converting a string to a float is similar to converting a string to an integer. Here is an example:
str = readline()println("Following is the ", typeof(str), ": ", str)num = parse(Float64, str)println("Following is in ", typeof(num), ": ", num)
Enter the input below
Here is the explanation of the code:
Line 1: We read a string.
Line 2: We print the given string and its type.
Line 3: We convert it to the float number.
Line 4: We print the number resulting from the given string and its type.
Let's now use the third parameter in the parse(type,str,base)
function to convert a string to an integer with a given base. Here we use base 5. The example is as follows:
str = readline()println("Following is the ", typeof(str), ": ", str)base = 5num = parse(Int64, str; base)println("Following is in ", typeof(num), ": ", num)println("(", num, ")base(", base, ")", " = ", str)
Enter the input below
Here is the explanation of the code:
Line 1: We read a string.
Line 2: We print the given string and its type.
Line 3: We specify the base.
Line 4: We convert it to the integer number with base 5
.
Line 5: We print the resultant number and its type.
Line 6: We express the relationship of the output with the input.
Note: If we don't pass the numerical string as an input, it will throw an exception.
Free Resources