Isssue with converting double to int

  • Thread starter Thread starter Curious
  • Start date Start date
C

Curious

Hi,

I have a double number and need to convert it to an int. Unfortunately
it simply drops the digit(s) after the decimal point. For example:

int requiredShares = (int)(1230.98);

The value of requiredShares is 1230. This is not right. The correct
number should be 1231 because that's the closest integer to 1230.98.

In summary, what I want is to round up to 1 if it's greater than .5
and round down to 0 if it's less than .5.

Anyone can tell me if there's any .NET utility that does what I want?
 
Curious said:
Hi,

I have a double number and need to convert it to an int. Unfortunately
it simply drops the digit(s) after the decimal point. For example:

int requiredShares = (int)(1230.98);

The value of requiredShares is 1230. This is not right. The correct
number should be 1231 because that's the closest integer to 1230.98.

In summary, what I want is to round up to 1 if it's greater than .5
and round down to 0 if it's less than .5.

Anyone can tell me if there's any .NET utility that does what I want?


int rounded = (int)System.Math.Round(1230.98, 0);


Mark
 
Curious said:
I have a double number and need to convert it to an int. Unfortunately
it simply drops the digit(s) after the decimal point. For example:

int requiredShares = (int)(1230.98);

The value of requiredShares is 1230. This is not right. The correct
number should be 1231 because that's the closest integer to 1230.98.
Conversion by truncation is a time-honored tradition in C-derived languages,
and you're a blasphemer for suggesting it's "not right". Just so you know. :-)
In summary, what I want is to round up to 1 if it's greater than .5
and round down to 0 if it's less than .5.
What do you want to round to when it's exactly 0.5, then?

Use Math.Round(), *then* convert the result. Math.Round() also has an
overload for specifying how to round numbers that are exactly between two
integers.
 
Jeroen:
What do you want to round to when it's exactly 0.5, then?

I don't have to be concerned about this situation.
Use Math.Round(), *then* convert the result. Math.Round() also has an
overload for specifying how to round numbers that are exactly between two
integers.

Thanks for letting me know. It works!
 
Back
Top