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

от admin

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.

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:

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

Каждый базовый тип данных занимает определенное количество байт памяти. Это накладывает ограничение на операции, в которые вовлечены различные типы данных. Рассмотрим следующий пример:

В данном коде мы столкнемся с ошибкой. Хотя и тип byte, и тип int представляют целые числа. Более того, значение переменной a, которое присваивается переменной типа byte, вполне укладывается в диапазон значений для типа byte (от -128 до 127). Тем не менее мы сталкиваемся с ошибкой на этапе компиляции. Поскольку в данном случае мы пытаемся присвоить некоторые данные, которые занимают 4 байта, переменной, которая занимает всего один байт.

Тем не менее в программе может потребоваться, чтобы подобное преобразование было выполнено. В этом случае необходимо использовать операцию преобразования типов (операция () ):

Операция преобразования типов предполагает указание в скобках того типа, к которому надо преобразовать значение. Например, в случае операции (byte)a , идет преобразование данных типа int в тип byte. В итоге мы получим значение типа byte.

Явные и неявные преобразования

Когда в одной операции вовлечены данные разных типов, не всегда необходимо использовать операцию преобразования типов. Некоторые виды преобразований выполняются неявно, автоматически.

Автоматические преобразования

Преобразования типов в языке Java

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

Автоматически без каких-либо проблем производятся расширяющие преобразования (widening) — они расширяют представление объекта в памяти. Например:

В данном случае значение типа byte, которое занимает в памяти 1 байт, расширяется до типа int, которое занимает 4 байта.

Расширяющие автоматические преобразования представлены следующими цепочками:

byte -> short -> int -> long

short -> float -> double

Автоматические преобразования с потерей точности

Некоторые преобразования могут производиться автоматически между типами данных одинаковой разрядности или даже от типа данных с большей разрядностью к типа с меньшей разрядностью. Это следующие цепочки преобразований: int -> float , long -> float и long -> double . Они производятся без ошибок, но при преобразовании мы можем столкнуться с потерей информации.

Явные преобразования

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

Потеря данных при преобразовании

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

Число 5 вполне укладывается в диапазон значений типа byte, поэтому после преобразования переменная b будет равна 5. Но что будет в следующем случае:

Результатом будет число 2. В данном случае число 258 вне диапазона для типа byte (от -128 до 127), поэтому произойдет усечение значения. Почему результатом будет именно число 2?

Число a, которое равно 258, в двоичном системе будет равно 00000000 00000000 00000001 00000010 . Значения типа byte занимают в памяти только 8 бит. Поэтому двоичное представление числа int усекается до 8 правых разрядов, то есть 00000010 , что в десятичной системе дает число 2.

Усечение рациональных чисел до целых

При преобразовании значений с плавающей точкой к целочисленным значениям, происходит усечение дробной части:

Здесь значение числа b будет равно 56, несмотря на то, что число 57 было бы ближе к 56.9898. Чтобы избежать подобных казусов, надо применять функцию округления, которая есть в математической библиотеке Java:

Преобразования при операциях

Нередки ситуации, когда приходится применять различные операции, например, сложение и произведение, над значениями разных типов. Здесь также действуют некоторые правила:

если один из операндов операции относится к типу double , то и второй операнд преобразуется к типу double

если предыдущее условие не соблюдено, а один из операндов операции относится к типу float , то и второй операнд преобразуется к типу float

если предыдущие условия не соблюдены, один из операндов операции относится к типу long , то и второй операнд преобразуется к типу long

иначе все операнды операции преобразуются к типу int

Так как в операции участвует значение типа double, то и другое значение приводится к типу double и сумма двух значений a+b будет представлять тип double.

Две переменных типа byte и short (не double, float или long), поэтому при сложении они преобразуются к типу int , и их сумма a+b представляет значение типа int. Поэтому если затем мы присваиваем эту сумму переменной типа byte, то нам опять надо сделать преобразование типов к byte.

Как double преобразовать в int 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.

3 Methods To Convert Double To Int In Java

Java Convert double to int

double and int are primitive data types in Java. Primitive data type int is used to represent integer values like 1,100 etc. whereas double represents floating-point numbers like 1.5, 100.005, etc.

Читать:
Как извлечь файлы из exe

In Java programs, under some scenarios, input data to the program is available in Java double, but it is required to round it off i.e. to convert a number to have it without any floating-point.

In such scenarios, this double value is required to be converted to an int data type. For Example, to print average weight, height, etc., or bill generated, it is more preferred to represent the value as integer instead of number with floating-point.

Let’s see the various ways of converting Java double to int one by one in detail.

#1) Typecasting

In this way of conversion, double is typecast to int by assigning double value to an int variable.

Here, Java primitive type double is bigger in size than data type int. Thus, this typecasting is called ‘down-casting’ as we are converting bigger data type values to the comparatively smaller data type.

Let’s understand this down-casting with the help of the following sample code:

Here is the program Output:

billAmt: 99.95
Your generated bill amount is: $99. Thank You!

Here, the “99.95” value is assigned to double variable billAmt.

This is converted to an integer by downcasting to an int data type as shown below.

Hence, when we print this bill value on the console:

We get the following output on the console:

As we can see, the floating-point double value “99.95” is now converted to int value “99”.

This is the simplest way of converting double to int. Let’s have a look at some more ways of doing so.

#2) Math.round(double d) Method

The round() method is a static method of the class Math.

Let’s have a look at the method signature below:

public static long round(double d)

This static method returns the nearest long value of the argument. If the argument value is NaN, then it returns 0. For the argument value negative infinity, less than or equal Long.MIN_VALUE, it returns Long.MIN_VALUE.

Similarly, for argument value positive infinity greater than or equal Long. MAX_VALUE., the method returns Long. MAX_VALUE.

d is a floating-point value that is required to be rounded to a long value.

Let’s try to understand how to use this Math.round(double d) method with the help of the following sample program. In this program, the bill amount is generated with floating-point i.e. in double data type value.

We are retrieving the integer value of the bill amount using the Math.round(double d) method as shown below:

Here is the program Output:

firstBillAmt :25.2
bill1 :25
Your first bill amount is : $25.
secondBillAmt :25.5
bill2 :26
Your second bill amount is : $26.

Here, we are assigning values to double variables:

These values are passed as an argument to Math.round(double d) method:

This converts the values into a long data type.

Further, these values are converted to int. This is because Math.round() returns a long value and we need to retrieve the int data type value.

This is done as follows:

So finally, when we print the bill amounts on the console, we see the following outputs:

Here the original double value was 25.2 which gets rounded off to the nearest integer 25.

Here, the original double value was 25.5 which gets rounded off to the nearest integer 26.

Notice the difference between the first bill and the second bill amount. This is because the second bill was 25.5 i.e. the number after the decimal point is 5 and for the first bill, it is 25.2 i.e. 2 after the decimal point.

#3) Double().intValue() Method

This is an instance method of Double class.

Let’s have a look at the method signature below:

public int intValue()

This method converts the value represented by Double-object to primitive data type int and returns the int value.

Let’s understand the use of the intValue() method of Double class with the help of the sample program below. In this program, the average score calculated is a floating-point numeric value in double data type.

This is converted to data type int using the Double().intValue() method:

Here is the program Output:

score1 :90.95
score2 :80.75
score3 :75.9
Average Score Number is :82.53333333333333
Congratulations ! You have scored :82

Here the floating-point score values are assigned to double variable as shown below:

The average calculated for these 3 scores is also a floating-point number double value:

This prints the following on the console:

Now, this double value is converted to int using Double(double d) constructor which returns Double-object. Method intValue() is invoked on this Double-object to return the value of primitive data type int as shown below.

Hence, when we print the average on the console:

It prints the following on the console i.e. int value 82 for double value 82.53333333333333:

Note: From Java9, the constructor Double(double d) has been deprecated. Hence, this is less preferred since Java9.

With this, we have covered the various ways for converting a value from primitive data type double to int Java primitive data type.

Let’s have look at some of the frequently asked questions about the double to int conversion.

Frequently Asked Questions

Q #1) How do you convert a double to an int in Java?

Answer: In Java, the primitive data type double can be converted to primitive data type int using the following Java class methods and ways:

  • typecasting: typecast to int
  • Math.round()
  • Double.intValue()

Q #2) What is int and double in Java?

Answer: In Java, there are various primitive data types like int, double, long, float to store a numeric value. Primitive data type int has size 4 bytes that holds whole numbers like 1 ,500 etc. starting from -2,147,483,648 to 2,147,483,647 .

Primitive data type double has size 8 bytes that hold floating-point numbers like 1.5, 500.5, etc. It can store 15 decimal digits. In Java, we can convert the value of the double data type to an int data type.

Q #3) How do you cast to int in Java?

Answer: In Java, the values in different data types can be converted to int like String to int or long to int by typecasting.

Also, there are various ways of casting double to int as shown below:

  • typecasting
  • Math.round()
  • Double.intValue()

Q #4) Can you add an int and double in Java?

Ans: One of the ways if the desired result is expected to be in int data type, then, first it needs to convert data to int value and then perform the addition. This conversion can be done using typecasting, Double().intValue() and Math.round() methods.

Conclusion

In this tutorial, we learned how to convert primitive double data type value to data type int in Java using the following class methods in detail with examples.

Похожие статьи