简体   繁体   中英

NumericUpDown Value turns to 0 when it is set as a float

So resizeWidth and resizeHeight are numericUpDown controls in this following code. Also, tempBitmapW and tempBitmapH are both floats.

float rW = (float)resizeWidth.Value;
float rH = (float)resizeHeight.Value;
rH = (float)Math.Truncate(tempBitmapH * ((float)rW / tempBitmapW));
int rsW = (int)rW;
int rsH = (int)rH;
resizeWidth.Value = rsW;
resizeHeight.Value = rsH;

Now when I debug this, rsW and rsH and rW and rH do not read as 0, none of them. But for some reason the numericUpDown controls throw an error as the Value 0 is out side the Minimum/Maximum range (the minimum is set to 1), so basically it is reading it as 0.

What have I done wrong?

You just dont understand correctly how casts work. Because of the way you are casting floats to int, you are getting 0. The float value might be 0.42 but that will cast to 0 in an integer.

You should check how casts work in detail, that will probably solve your problem.

To expand on squelos' answer- it sounds like perhaps the moment when you're looking at the values in the debugger and the moment when the exception is being thrown are two different moments in time. If you're getting an exception saying the value is zero- it's probably because the value is zero.

The reason it might become zero is because the cast from float to int always rounds down to the nearest integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM