Isssue with converting double to int

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?
 
M

Mark Salsbery [MVP]

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
 
J

Jeroen Mostert

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.
 
C

Curious

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top