Преобразование строки в число в Julia
Julia - это гибкий, динамичный и высокоуровневый язык программирования, который можно использовать для написания любых приложений. Кроме того, многие из его функций можно использовать для численного анализа и вычислений. Джулия широко используется в машинном обучении, визуализации и науке о данных. Julia допускает преобразование типов для совместимых типов данных. У Джулии есть встроенный метод синтаксического анализа, который позволяет преобразовывать строку в числовой тип данных.
Строку можно преобразовать в желаемый числовой тип данных, пока она не станет недопустимой. Мы также можем указать базу для преобразования, например, десятичную, двоичную, восьмеричную или шестнадцатеричную.
Syntax: parse(T::Type, str, base=Int)
Parameters:
Type: Specifies the datatype to which the String is to be converted.
str: It is the String that is to be converted to the specified datatype.
base: This is optional. Required only if the String must be converted to a Number of specific bases.
Ниже приведены способы преобразования из String в Number в Julia:
Преобразование строкового ввода в число
The string input is taken from the user using the readline() method of Julia. Next, the parse() method is used to convert the String into Integer datatype. The typeof() method outputs the datatype of the resulting integer.
Julia
# reads the string a = readline() # prints the string println(a) # parsing the string to integer print (typeof(parse(Int64, a))) |
Выход :
Преобразование строки в число с некоторой базой
The string input is taken from the user using the readline() method of Julia. Next, the parse() method is used to convert the String into Integer datatype with the given base(here octal). The typeof() method outputs the datatype of the resulting integer.
Julia
# Taking User Input println( "Enter the number" ) a = readline() println( "Entered the number: " a) # 8 is the octal base println(parse(Int64, a, 8 )) # Getting Type of data print (typeof(parse(Int64, a, 8 ))) |
Выход :
Получение строкового ввода и базы от пользователя и преобразование их в число
The string input and required base are taken from the user using the readline() method of Julia. The parse() method converts the base into Integer(Int64). Next, the parse() method is used to convert the String into Integer datatype with the given base(here hexadecimal). The typeof() method outputs the datatype of the resulting integer.
Julia
# Taking String from user println( "Enter the number" ) a = readline() println( "Entered the number: " a) # Taking base from user println( "Enter the base(10,8,16,2)" ) base = readline() println( "Entered base: " base) # Converting to Number println(parse(Int64, a, parse(Int64,base))) print (typeof(parse(Int64, a, parse(Int64,base)))) |
Выход :
Преобразовать строку в Float64
The string input is taken from the user using the readline() method of Julia. Next, the parse() method is used to convert the String into Float datatype. The typeof() method outputs the datatype of the resulting float value.
Julia
# parsing string into float println(parse(Float64, "123.345" )) print (typeof(parse(Float64, "123.345" ))) |
Выход :
Недопустимая строка вызывает исключение
Since the given string cannot be converted into Float type the parse() method throws an error.
Julia
# error will be thrown as string # is not a valid float representation print (parse(Float64, "123.345a" )) |
Выход :