When you convert double to int, the precision of the value is lost. For example, when you convert 4.8657 (double) to int, the int value will be 4. Primitive int does not store decimal numbers, so you will lose 0.8657.

In your case, 0.7 is a double value (floating point treated as double by default unless mentioned as float - 0.7f). When you calculate price*much*0.7, the answer is a double value and so the compiler wouldn't allow you to store it in a type integer since there could be a loss of precision. That's what is "possible lossy conversion", you may lose precision.

So what could you do about it? You need to tell the compiler that you really want to do it. You need to tell it that you know what you are doing. So explicitly convert double to int using the following code:

int total2= (int) (price*much*0.7);
 /*(int) tells compiler that you are aware of what you are doing.*/
 //also called as type casting

In your case,since you are calculating the cost, I'll suggest you to declare variable total2 as the type double or float.

double total2=price*much*0.7;
 float total2=price*much*0.7;
 //will work
Answer from Mathews Mathai on Stack Overflow
Top answer
1 of 2
17

When you convert double to int, the precision of the value is lost. For example, when you convert 4.8657 (double) to int, the int value will be 4. Primitive int does not store decimal numbers, so you will lose 0.8657.

In your case, 0.7 is a double value (floating point treated as double by default unless mentioned as float - 0.7f). When you calculate price*much*0.7, the answer is a double value and so the compiler wouldn't allow you to store it in a type integer since there could be a loss of precision. That's what is "possible lossy conversion", you may lose precision.

So what could you do about it? You need to tell the compiler that you really want to do it. You need to tell it that you know what you are doing. So explicitly convert double to int using the following code:

int total2= (int) (price*much*0.7);
 /*(int) tells compiler that you are aware of what you are doing.*/
 //also called as type casting

In your case,since you are calculating the cost, I'll suggest you to declare variable total2 as the type double or float.

double total2=price*much*0.7;
 float total2=price*much*0.7;
 //will work
2 of 2
8

You are trying to assign price* much* 0.7, which is a floating point value (a double), to an integer variable. A double is not an exact integer, so in general an int variable cannot hold a double value.

For instance, suppose the result of your calculation is 12.6. You can't hold 12.6 in an integer variable, but you could cast away the fraction and just store 12.

If you are not worried about the fraction you will lose, cast your number to an int like this:

int total2 = (int) (price* much* 0.7);

Or you could round it to the nearest integer.

int total2 = (int) Math.round(price*much*0.7);
🌐
Reddit
reddit.com › r/learnprogramming › [java] possible lossy conversion from double to int error.
r/learnprogramming on Reddit: [Java] Possible lossy conversion from double to int error.
March 21, 2014 -

First post, sorry if I make a mistake. Believe I didn't miss any rules.

Code: https://jsfiddle.net/80wLpmj1/

Error: Possible lossy conversion from double to int error. int birthrate = 1.0 / 7.0 ^

It does this for birthrate, deathrate, and immigrationrate. I've changed everything from "int" to "double" and it compiles, but then when executed I get decimals where I don't want them.

People also ask

Can the Math.round() Function Help in Double To Int Conversion?
No, the Math.round() function will not help in double to int conversion. It will only round off the given double value to the nearest long value. So, you’ll again need to go for typecasting to convert the resulting number from long to int.
🌐
positioniseverything.net
positioniseverything.net › home › possible lossy conversion from double to int: fast solutions
Possible Lossy Conversion From Double to Int: Fast Solutions - ...
Will the Lost Data Be Recoverable After Conversion From Double To Int?
No, the data lost while converting double to int won’t be recoverable. But if you want to keep the double value, you might like to store it in a variable before converting the same. This way, you’ll have a variable with a double value.
🌐
positioniseverything.net
positioniseverything.net › home › possible lossy conversion from double to int: fast solutions
Possible Lossy Conversion From Double to Int: Fast Solutions - ...
How Will the Number Be Rounded After Typecasting It To Int?
The number will always be rounded down irrespective of the digit after the decimal point. So, whether the number is 3.4 or 3.4, typecasting will make it 3. In this case, if the number is greater than 3.5, the typecasting will round it off to 4.
🌐
positioniseverything.net
positioniseverything.net › home › possible lossy conversion from double to int: fast solutions
Possible Lossy Conversion From Double to Int: Fast Solutions - ...
🌐
Coderanch
coderanch.com › t › 708642 › java › error-incompatible-types-lossy-conversion
getting error: incompatible types: possible lossy conversion from double to int (Beginning Java forum at Coderanch)
It looks like the test is trying to pass double values and your methods only take int values. That's the "lossy conversion" referred to in the error message, meaning you could potentially lose decimals since the receiving variable is an int.
🌐
Baeldung
baeldung.com › home › java › lossy conversion in java
Lossy Conversion in Java | Baeldung
January 8, 2024 - The double values can be too large or too small for an int and decimal values will get lost in the conversion. Hence, it is a potential lossy conversion.
🌐
Studocu
studocu.com › university of maryland baltimore county › introduction to computer programming › question
[Solved] java compiler incompatible types possible lossy conversion - Introduction to Computer Programming (IS 147 ) - Studocu
March 5, 2025 - The error message you are encountering, "incompatible types: possible lossy conversion from double to int," indicates that you are trying to assign a double value to an int variable without explicit casting.
🌐
Brainly
brainly.in › computer science › secondary school
Possible lossy conversion from double to int - Brainly.in
June 25, 2024 - The error "possible lossy conversion from double to int" occurs when you try to assign a double value to an integer variable.
Find elsewhere
🌐
Position Is Everything
positioniseverything.net › home › possible lossy conversion from double to int: fast solutions
Possible Lossy Conversion From Double to Int: Fast Solutions - Position Is Everything
November 12, 2025 - A possible lossy conversion from double to int error can appear when you try to convert a bigger data type (double) to a smaller data type (int).
Top answer
1 of 2
13

The first problem is a simple typo. Java is case sensitive, so cube and Cube mean different things. Solution: 1) be consistent, and 2) use names starting with lowercase letters for method names ... as per the Java style guides.


The second problem is due to the method signature for Math.pow; see the javadoc. It returns the result as a double. You then attempte to return the double as an int, and that is a lossy conversion.

The solutions include:

  return b * b * b;   // i.e. don't use `pow`.

or

  return (int) Math.pow(b, 3);

The second one directly addresses your compilation error by casting the double return to an int. This is the way you tell the compiler that the lossy conversion is actually OK.

The lossy conversion error message you are seeing refers to that fact for large enough values of b, the result of Math.pow(b, 3) will be too large to be represented as an int1. With the type cast in place, Java will convert a floating point number that is "too large" into Integer.MAX_VALUE.

The first solution is faster and simpler code, but if b is too large, the calculations will silently overflow and you will get a nonsense answer.


UPDATE - If you wanted overflow to always be treated as an error then:

return Math.multiplyExact(b, Math.multiplyExact(b, b));

or

return Math.toIntExact((long) Math.pow(b, 3));

or variations on the above.


1 - Actually, the compiler doesn't know about the semantics of pow, so it doesn't know about "... for large enough values of b ...". But it does know that if the method call did return a large enough value, then the conversion would be lossy. That's why the message says "possible lossy conversion".

2 of 2
1

Two problems:

  1. Letter case is important: Cube is not the same as cube.
  2. Your function cube(int) returns an integer, but the output of Math.pow is a double.

You should probably change cube() to return a double.

Then you have more code to write in the main method to use the results of calling cube.

🌐
Sololearn
sololearn.com › en › Discuss › 1794556 › what-does-it-mean-possibly-lossy-conversion-from-double-to-int
What does it mean "possibly lossy conversion from double to int" | Sololearn: Learn to code for FREE!
When going from a larger number-type to a smaller one, you will get an error unless you use type casting The following example is in C# long MyLong = 12345 int MyInt = (int)MyLong It is done using "(datatype)" Hope this helps ... I want to say that i have written a program in that a error is showing "possibly lossy conversion from double to int" And i am not understanding what does it mean
🌐
Java-Forum
java-forum.org › foren › java - programmierung › java basics - anfänger-themen
possible lossy conversion from double to int
January 27, 2021 - In dem Fall gibt die Methode ein double Wert zurück. Dies ist eine Fliesskommazahl. Ds ist somit eine Zahl, die zum einen Nachkommastellen hat und zum anderen auch sehr groß sein kann (da es eine Exponentielle Darstellung ist). Also wenn da ein Wert 3,5 drin ist (oder 3.5 - in Java wird der . statt dem , verwendet), dann kann da nur die Ganzzahl 3 in den Int übernommen werden.
🌐
Rollbar
rollbar.com › home › how to handle the incompatible types error in java
How to Handle the Incompatible Types Error in Java | Rollbar
September 28, 2022 - 1(a) shows how attempting to assign the values of the two double variables a and b to the int variables x and y results in the incompatible types error at compile-time. Prefixing the variables on the right-hand side of the assignment with the int data type in parenthesis (lines 10 & 11 in Fig. 1(b)) fixes the issue. Note how both variables lost their decimal part as a result of the conversion, but only one kept its original value—this is exactly why the error message reads possible lossy conversion from double to int and why the incompatible types error is raised in this scenario.
🌐
CodeChef Discuss
discuss.codechef.com › general
Problem regarding possible lossy conversion from double to int - general - CodeChef Discuss
March 1, 2017 - I have been making a program to find the number of trailing zeroes at the end of the factorial of a number. The program first of all takes the input ‘a’- the number of the numbers it has to operate on. Then it takes ‘a’ number of inputs and calculates number of zeroes at the end of ...
🌐
Brainly
brainly.com › computers and technology › high school › what is a possible lossy conversion from double to int?
[FREE] What is a possible lossy conversion from double to int? - brainly.com
When converting a double to an int, a lossy conversion occurs because the fractional part of the double value is discarded. This means only the whole number part is kept, which can lead to a loss of precision.
🌐
Reddit
reddit.com › r/learnjava › possible lossy conversion from double to int
r/learnjava on Reddit: Possible Lossy Conversion from Double to Int
October 16, 2019 -

Does anyone know why I am getting this error even though all the relevant variables are doubles?

/*
This program will roll a pair of dice 10000 times, 11 separate times
to find out the average number of rolls to achieve the desired total
of two dice.
*/

public class Practice {

	/*
	The main method will iterate all the possible totals then call the 
	computeRoll function to roll the dice 10000 times. The main method
	will then print a table showing the average number of rolls to get
	a given total per possible total.
	*/

	public static void main (String [] args) {

		int i;
		double averageNumberOfRolls;
		double [] averageTable;

		averageTable = new double [13]; 

		System.out.println ("This program will roll a pair of dice 10000 times for each possible total.");
		System.out.println ("It will then create a table for the average number of rolls it took to achieve that total.");
		System.out.println ();


		for (i = 2; i <= 12; i ++) {

			averageNumberOfRolls = computeRoll (i);
			averageTable [i] = averageNumberOfRolls;
		}
	
		System.out.println ("Total On Dice    Average Number of Rolls");
		System.out.println ("-------------    -----------------------");

		
		for (i = 2; i <= 12; i ++) {

			System.out.println ("     " + i + "               " + averageTable [i]);
		}

		System.out.println ();
	}

	/*
 	This method will roll two dice randomly until it achieves 10000 rolls. It will record the
 	average number of rolls it took.
 	*/

  	private static int computeRoll (int goal) {

    	int dice1;
    	int dice2;
    	int result;
    	double attempts;
    	double numberOfTimesGoalWasHit;
    	double average;

    	numberOfTimesGoalWasHit = 0.0;
    	attempts = 0.0;

   
    	do { 

      		result = 0;

      		dice1 = (int)(Math.random () * 6) + 1;
      		dice2 = (int)(Math.random () * 6) + 1;
      		result = dice1 + dice2;
      		attempts ++;


      		if (result == goal) {

      			numberOfTimesGoalWasHit ++;
      		}

     	} while (attempts < 10000.0);
  
     	average = attempts / numberOfTimesGoalWasHit;

     	return average;
  	}
}
🌐
CSDN
blog.csdn.net › GodTheTang › article › details › 121028599
出现incompatible types: possible lossy conversion from double to int错误-CSDN博客
在Java中遇到`incompatible types: possible lossy conversion from double to int`错误时,表示你正尝试将高精度的`double`类型值直接赋给低精度的`int`类型变量,导致可能丢失小数部分以下是逐步分析和解决方法...
🌐
Reddit
reddit.com › r/javahelp › possible lossy conversion from double to int
r/javahelp on Reddit: Possible lossy conversion from double to int
October 10, 2019 -

I'm working on a school project right now and I am getting an error which I have no idea how to fix. Any help is appreciated

package Assignment_3_1; //directory
import Media.*;
import static java.lang.Math.*;
import static java.awt.Color.*;

public class Forest{ //class

private TurtleDisplayer display; //display
private Turtle t; //pen

    public Forest(){ //constructor
        //instance/global variables
        display = new TurtleDisplayer(); //initialize display
        t = new Turtle(0); //initialize pen
        display.placeTurtle(t); //place the pen on the display
        drawLeaves(30);
        display.close(); //close display
    }
    private void drawLeaves(double radius){ //this method draws trees' leaves     given a double radius (width of leaves)
        for(int i = 0; i <=7; i++){ //repeat the below code a set number of times
        //below code draws a line, 45 degrees the right of the previous one
        t.setPenWidth(radius*2.0);
        t.setPenColor(GREEN);
        t.right(PI/4);
        t.penDown();
        t.forward(radius);
        t.penUp();
        t.backward(radius);
        }
    }
    private void drawTrunk(double height){ //draws a trunk given a double height

    }
    public static void main(String[] args){Forest s = new Forest();};
   }

The error happens at line:

t.setPenWidth(radius*2.0);

Once again, I have no idea what's happening here

Top answer
1 of 2
2

The method setPenWidth probably takes an integer parameter. Your radius is a double. In order to use the radius value for the method Java needs to convert it to an integer by cutting the decimal digits off. So your value might lose accuracy.

2 of 2
1

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.