Как из строки сделать число java

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:

How do I convert a String to an int in Java?

Ramesh R's user avatar

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.

nanofarad's user avatar

lukastymo's user avatar

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.

Peter Mortensen's user avatar

Peter Mortensen's user avatar

Billz's user avatar

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.

Jonah Graham's user avatar


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:

ROMANIA_engineer's user avatar

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:

Как преобразовать строку в число

Очень часто бывает следующая задача: конвертировать строку в числовой тип. В Java это можно сделать разными способами. Главное – учитывать максимальную размерность данных и точность (для дробных чисел).

Преобразование строки в целое число

Для конвертации строк в целые числа есть методы Integer.parseInt и Long.parseLong для конвертации в типы int и long, соответственно.

Простой способ получить int из строки:

Примечание: метод Integer.parseInt корректно преобразует числа, входящие в диапазон типа int (-2147483648..2147483647). Если число выходит за эти границы или содержит недопустимые символы, будет выброшено исключение NumberFormatException:

Если вам нужны числа большей размерности, чем int, воспользуйтесь методом Long.parseLong:

Например, можно использовать такой утилитарный метод, который при невозможности корректно распарсить строку вернёт ноль:

Преобразование строки в дробное число

Для преобразования строк в дробные числа можно воспольоваться методами Float.parseFloat и Double.parseDouble, которые производят числа типов float и double, соответственно:

Стоит заметить, что лучше пользоваться double вместо float из-за повышенной точности double.

Преобразование больших чисел

Если вам не хватает размерности для хранения чисел типах long и double, вы можете использовать BigInteger и BigDecimal:

Здесь не получится воспользоваться преобразованием в int из-за выхода за размеры int; получится преобразовать в double, но с потерей точности.


В данной статье мы описали стандартные методы преобразования строки в число. При выборе метода нужно учитывать размерность типов, к которому приводится число.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *