user818700
user818700

Reputation:

Casting int to double and rounding off to last whole number

I'm stuck with a little issue here, say you have the following code:

int whole = 0;
double decimal = 88.00

whole = decimal / 1.5; //now the answer is 58.66

So here's the issue, explicitly casting a double to an int is easy enough. But if I do this now 'whole' is going to be set to 59. This - is not so good, I want it to be set to the last whole number (being 58).

How do you do this in C#?

Upvotes: 3

Views: 315

Answers (6)

Ionică Bizău
Ionică Bizău

Reputation: 113385

This will convert the double value into int:

whole = (int)(decimal / 1.5);

Also, you can use Math.Floor(doubleValue).

Upvotes: 0

user1277476
user1277476

Reputation: 2909

If you need rounding, it's pretty common to use: whole = (int)(decimal / 1.5 + 0.5); Without the 0.5, you're truncating, not rounding.

If you have a rounding function in your math libraries, that's good too. Some of these will do the odd/even thing for rounding 0.5 to avoid a little bit of data skew.

Upvotes: 0

Kendall Frey
Kendall Frey

Reputation: 44326

To round doubles to integers, you have 4 basic math functions:

  1. Math.Round() - Rounds to the nearest whole number (or user specified number of deciml places), and lets you choose to round middle points up or down.

  2. Math.Floor() - Rounds to the first whole number toward negative infinity.

  3. Math.Ceiling() - Rounds to the first whole number toward positive infinity.

  4. Math.Truncate() - Rounds to the first whole number toward zero.

I think you want either Floor or Truncate. Both round down for positive numbers, but Truncate rounds -3.6 to -3, while Floor rounds it to -4.

Casting to int does the same as truncating, so you can use that if you prefer.

Upvotes: 7

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

If you cast double to int, the answer will NOT be 59 -- it will be 58. When casting double to int, the value will be rounded towards zero. So, this is sufficient:

int whole = 0;
double x = 88.00;
whole = (int)(x / 1.5); // whole will be 58

Upvotes: 2

Simon Whitehead
Simon Whitehead

Reputation: 65079

Math.Floor:

whole = (int)Math.Floor(decimal / 1.5);

Upvotes: 4

Kevin Gosse
Kevin Gosse

Reputation: 39007

Use Math.Floor if you want to round to the last whole number, and Math.Ceiling if you want to round to the next.

Upvotes: 1

Related Questions