Kiran Waje
Kiran Waje

Reputation: 43

Type conversion in C#, Explicit casting to int and Convert.ToInt32

In my following code

long Price = 148920000;
long PRICE = 1000000;
double Multiplier = 100.00;
int Value = (int)(((double)Price / PRICE) * Multiplier);

I expect Value as 14892 but in C# it is coming 14891....

Upvotes: 4

Views: 310

Answers (3)

MethodMan
MethodMan

Reputation: 18843

If you are not familiar on how to get the values that you want to convert this answer will give you what you are looking for

long Price = 148920000;
long PRICE = 1000000;
double Multiplier = 100.00;
var Value = (Convert.ToInt32(Math.Round((double)Price / (double)PRICE) * Multiplier));

or a another version without using var keyword yields the same results

long Price = 148920000;
long PRICE = 1000000;
double Multiplier = 100.00;
int Value = (int)(Math.Round((double)Price / (double)PRICE) * Multiplier);

Answer = 14892

Upvotes: 0

WraithNath
WraithNath

Reputation: 18013

not on a development machine at the mo but can you try this?

long Price = 148920000;
long PRICE = 1000000;
double Multiplier = 100.00;
checked
{
int Value = (int)(((double)Price / PRICE) * Multiplier);
}

should throw an error if it overflows

http://msdn.microsoft.com/en-gb/library/74b4xzyw(v=vs.71).aspx

Upvotes: 0

Pieter Geerkens
Pieter Geerkens

Reputation: 11883

Floating-point arithmetic id ALWAYS approximate. Use one of Math.Round(), Math.Floor(), or Math.Ceiling() to control how doubles/floats are converted to any int type. Or look at using Decimal instead.

Upvotes: 4

Related Questions