Question

I've got the following line of code:

int destHeight = (int)(sourceHeight * percent);

I'm using this in a part of a process that crops images to thumbnails while maintaining aspect ratio.

The problem is outlined as such:

percent = 0.08680555,

sourceHeight = 576,

the calculation results in 50.0, but when assigned to destHeight as an int, it changes to 49.

How can I fix this?

Was it helpful?

Solution

It's not really 50:

double percent = 0.08680555;
int sourceHeight = 576;

System.out.println(sourceHeight * percent);  // e.g. Java
49.9999968

Casting as int truncates the fractional part, leaving 49.


You can try using some sort of round() function:

double percent = 0.08680555;
int sourceHeight = 576;

System.out.println(Math.round(sourceHeight * percent));
50

OTHER TIPS

You should round your number to fix the problem: int destHeight = (int)(sourceHeight * percent + 0.5);

casting to int will truncate. Use Convert.ToInt32() instead:

int destHeight = Convert.ToInt32(sourceHeight * percent);

arshajii is correct. When casting from floating point (e.g. double) to integer, the decimal is normally truncated. (In Java the integer types are byte, short, int, and long.) To get 50, you must use a rounding function. Java example:

double percent = 0.08680555;
int sourceHeight = 576;
int destHeight = (int) Math.round(sourceHeight * percent);
System.out.println(destHeight);

50
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top