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?

有帮助吗?

解决方案

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

其他提示

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top