C#中的类型转换,显式地强制转换为int和Convert.ToInt32

4
在我的以下代码中
long Price = 148920000;
long PRICE = 1000000;
double Multiplier = 100.00;
int Value = (int)(((double)Price / PRICE) * Multiplier);

我期望的值是14892,但在C#中却出现了14891...


1
请不要使用只有大小写不同的变量名,除非您参加混淆代码比赛。 - Konamiman
如果您想要精确的值,请使用十进制 http://ideone.com/TFA2q5 这篇文章值得一读:http://csharpindepth.com/Articles/General/Decimal.aspx - Tim Schmelter
3个回答

4

浮点算术运算始终是近似值。使用 Math.Round()、Math.Floor() 或 Math.Ceiling() 控制 double/float 转换为任何 int 类型的方式。或者考虑使用 Decimal 替代。


0

0
如果您不熟悉如何获取您要转换的值,本答案将为您提供所需内容。
long Price = 148920000;
long PRICE = 1000000;
double Multiplier = 100.00;
var Value = (Convert.ToInt32(Math.Round((double)Price / (double)PRICE) * Multiplier));

或者另一个版本,不使用 var 关键字也能产生相同的结果。

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

答案 = 14892


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接