Перейти к содержимому

Как double преобразовать в int

  • автор:

Java – Convert double to int example

In this tutorial, we will learn how to convert double to int in Java. As we know double value can contain decimal digits (digits after decimal point), so when we convert double value with decimal digits to int value, the decimal digits are truncated. In this java tutorial, we will see three ways to convert a double value to int. Out of these 3 ways there is one way in which you can round of the double value to nearest integer value.

1. Convert double to int using typecasting
2. Convert double to int using Math.round() – This ensures that the decimal digits double value is rounded of to the nearest int value.
3. Convert double to int using Double.intValue()

1. Java – double to int conversion using type casting

To typecast a double value to integer, we mention int keyword in the brackets before the decimal double value. The only downside of conversion using typecasting is that the double value is not rounded of, instead the digits after decimal are truncated. We can solve this issue by using Math.round() method which we have discussed in the second example.

Java Convert double to int using typecasting

Output: Here is the output of the above program –

2. Java – Convert double to int using Math.round()

In this example we are converting the double value to integer value using Math.round() method. This method rounds of the number to nearest integer. As you can see in the output that the double value 99.99 is rounded of to the nearest int value 100 .

Java double to int conversion using math.round() method

Output:

Convert double to int in Java using Double.intValue()

In this example we are using Wrapper class Double . This is same as typecasting method, where the digits after decimal are truncated.

Convert double to int in Java using Double.intValue() method

Output:

Top Related Articles:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Convert Double to Integer in Java

Given a Double real number. Write a Java program to convert the given double number into an Integer (int) in Java.

Examples:

Double: The double data type is a double-precision 64-bit IEEE 754 floating-point. Its value range is endless. The double data type is commonly used for decimal values, just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0.

Integer: The Integer or int data type is a 32-bit signed two’s complement integer. Its value-range lies between – 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is – 2,147,483,648 and maximum value is 2,147,483,647. Its default value is 0. The int data type is generally used as a default data type for integral values unless if there is no problem about memory.

Approaches

There are numerous approaches to do the conversion of Double datatype to Integer (int) datatype. A few of them are listed below.

double в int

Преобразовать 2 числа int в 1 число float(double) | double int1.int2
Всем привет. Изучая азы C++, столкнулся с такой проблемой. Есть два значения типа int, их.

Double, int , long double
Как вычислить диапазоны типов вручную указанных в название темы?

Сообщение от GetHelp
Сообщение от newbie666
Сообщение от hwmlex
Сообщение от newbie666

Добавлено через 25 секунд

Сообщение от hwmlex
Сообщение от LuxArt
Сообщение от GetHelp
Сообщение от LuxArt

а ведь и правда надо еще как то округлять.

Добавлено через 1 минуту

Сообщение от newbie666

ну это не правда

мне нужно не округление вниз или вверх, мне нужно округление по правилам математики, т.е. если меньше 0,5 то 0, если больше 0,5 то 1 и т.п. и т.п.

п.с. правда, я проверил

Сообщение от GetHelp
Сообщение от Hunter13ua

я конечно ваш код ни хрена не понял, потому что знаю только чистый си, си++ не вкуриваю вообще. но по моему в функции бред какой то.

Добавлено через 2 минуты

Сообщение от newbie666

это округляет опять таки до ближайшего нижнего разряда, я же сказал мне это не надо. т.е. попробуйте округлить вашим способом например 1,7, получится 1, а должно 2

Добавлено через 1 минуту
вот заготовка ежели что

Сообщение от GetHelp
Сообщение от scenotaph

оо. да вот теперь выдает 2 действительно. хотя я и не понимаю почему оно тогда не чекнуло мне ошибку при считывании если запятая вместо точки на это влияет? и по прежнему логика у функции странная (предыдущий пост)

Добавлено через 2 минуты
даже не 1,75, а например попробуйте взять 1,45 или 1,49 и получите 1, а по правилам математики должно выходить 2.

Преобразование Double в Integer в Java

При работе с числовыми данными в Java, часто возникает необходимость преобразования одного числового типа в другой. Например, когда есть число с плавающей точкой типа Double, и его нужно преобразовать в целое число типа Integer.

При попытке выполнить приведенный выше код, возникнет исключение java.lang.ClassCastException с сообщением об ошибке «java.lang.Double incompatible with java.lang.Integer». Это происходит потому что, в отличие от некоторых других языков программирования, Java не позволяет прямое приведение типов между Double и Integer.

Как преобразовать Double в Integer в Java?

Решение этой проблемы лежит в использовании метода intValue() , который является частью класса java.lang.Double . Метод intValue() преобразует значение объекта Double в int.

Теперь, когда код выполняется, integerNumber получит значение 123. Обратите внимание, что дробная часть числа просто отбрасывается вместо округления до ближайшего целого числа.

Если требуется округление до ближайшего целого числа, можно использовать метод Math.round() .

В этом случае, если дробная часть числа 0.5 или больше, число округляется до ближайшего большего целого числа. Если дробная часть числа меньше 0.5, число округляется до ближайшего меньшего целого числа.

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

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