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

In my next code

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

I expect the value to be equal to 14892, but in C # it will occur 14891 ....

+4
source share
3 answers

If you are not familiar with how to get the values ​​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 another version without using the var keyword gives 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

0
source

A floating point arithmetic identifier is ALWAYS approximated. Use one of Math.Round (), Math.Floor () or Math.Ceiling () to control the conversion of double / float to any int type. Or use Decimal instead.

+4
source

not on a development machine in 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 cause an error if it overflows

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

0
source

Source: https://habr.com/ru/post/1469017/


All Articles