Java: преобразование строки в число и наоборот
В некоторых случаях при программировании на Java нам нужно выполнить преобразование строки в число или числа в строку. Это бывает, если мы имеем величину определённого типа и желаем присвоить эту величину переменной другого типа. Преобразования типов в Java осуществляются разными способами, давайте рассмотрим наиболее популярные из них.
Как преобразовать строку в число в Java?
Речь идёт о преобразовании String to Number. Обратите внимание, что в наших примерах, с которыми будем работать, задействована конструкция try-catch. Это нужно нам для обработки ошибки в том случае, когда строка содержит другие символы, кроме чисел либо число, которое выходит за рамки диапазона предельно допустимых значений указанного типа. К примеру, строку «onlyotus» нельзя перевести в тип int либо в другой числовой тип, т. к. при компиляции мы получим ошибку. Для этого нам и нужна конструкция try-catch.
Преобразуем строку в число Java: String to byte
Выполнить преобразование можно следующими способами:
C помощью конструктора:
С помощью метода valueOf класса Byte:
С помощью метода parseByte класса Byte:
А теперь давайте посмотрим, как выглядит перевод строки в массив байтов и обратно в Java:
Преобразуем строку в число в Java: String to int
Здесь, в принципе, всё почти то же самое:
Используем конструктор:
Используем метод valueOf класса Integer:
Применяем метод parseInt:
Аналогично действуем и для других примитивных числовых типов данных в Java: short, long, float, double, меняя соответствующим образом названия классов и методов.
Как преобразовать число в строку в Java?
Теперь поговорим о преобразовании числа в строку (Number to String). Рассмотрим несколько вариантов:
Преобразовать строку в int в C++
В этом посте мы обсудим, как преобразовать строку в int в C++.
1. Использование std::stoi функция
Стандартный подход заключается в использовании std::stoi функция преобразования строки в целое число. stoi функция была введена в C++11 и определена в заголовке <string> . Он бросает std::invalid_argument или же std::out_of_range исключение при неправильном вводе или целочисленном переполнении соответственно. Стоит отметить, что он будет преобразовывать такие строки, как 10xyz в целое число 10 .
How do I convert a String to an int in Java?
![]()
If you look at the Java documentation you’ll notice the "catch" is that this function can throw a NumberFormatException , which you can handle:
(This treatment defaults a malformed number to 0 , but you can do something else if you like.)
Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8’s Optional , makes for a powerful and concise way to convert a string into an int:
For example, here are two ways:
There is a slight difference between these methods:
- valueOf returns a new or cached instance of java.lang.Integer
- parseInt returns primitive int .
The same is for all cases: Short.valueOf / parseShort , Long.valueOf / parseLong , etc.
![]()
![]()
Well, a very important point to consider is that the Integer parser throws NumberFormatException as stated in Javadoc.
It is important to handle this exception when trying to get integer values from split arguments or dynamically parsing something.
![]()
![]()
![]()
An alternate solution is to use Apache Commons’ NumberUtils:
The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.
![]()
Integer.decode
You can also use public static Integer decode(String nm) throws NumberFormatException .
It also works for base 8 and 16:
If you want to get int instead of Integer you can use:
![]()
Currently I’m doing an assignment for college, where I can’t use certain expressions, such as the ones above, and by looking at the ASCII table, I managed to do it. It’s a far more complex code, but it could help others that are restricted like I was.
The first thing to do is to receive the input, in this case, a string of digits; I’ll call it String number , and in this case, I’ll exemplify it using the number 12, therefore String number = "12";
Another limitation was the fact that I couldn’t use repetitive cycles, therefore, a for cycle (which would have been perfect) can’t be used either. This limits us a bit, but then again, that’s the goal. Since I only needed two digits (taking the last two digits), a simple charAt solved it:
Having the codes, we just need to look up at the table, and make the necessary adjustments:
Now, why double? Well, because of a really "weird" step. Currently we have two doubles, 1 and 2, but we need to turn it into 12, there isn’t any mathematic operation that we can do.
We’re dividing the latter (lastdigit) by 10 in the fashion 2/10 = 0.2 (hence why double) like this:
This is merely playing with numbers. We were turning the last digit into a decimal. But now, look at what happens:
Without getting too into the math, we’re simply isolating units the digits of a number. You see, since we only consider 0-9, dividing by a multiple of 10 is like creating a "box" where you store it (think back at when your first grade teacher explained you what a unit and a hundred were). So:
And there you go. You turned a String of digits (in this case, two digits), into an integer composed of those two digits, considering the following limitations:
Converting Between Numbers and Strings
Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.
The Number subclasses that wrap primitive numeric types ( Byte , Integer , Double , Float , Long , and Short ) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:
The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:
Converting Numbers to Strings
Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:
Each of the Number subclasses includes a class method, toString() , that will convert its primitive type to a string. For example:
The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point: