将double转换为int并保留小数c#
我有一个赋值,我应该创建一个方法,将十进制数(double)转换成int,但小数也应该保留 例如。2,33——放入方法并生成-->233 这就是我到目前为止所做的,它只生成一个四舍五入的数字将double转换为int并保留小数c#,c#,int,double,converter,C#,Int,Double,Converter,我有一个赋值,我应该创建一个方法,将十进制数(double)转换成int,但小数也应该保留 例如。2,33——放入方法并生成-->233 这就是我到目前为止所做的,它只生成一个四舍五入的数字 static int MakeDoubleInt(double x) { int y = (int)x; return y; } 将double转换为字符串,再次删除,TryParse到int static int MakeDoubleInt(do
static int MakeDoubleInt(double x)
{
int y = (int)x;
return y;
}
将
double
转换为字符串,再次删除,
TryParse到int
static int MakeDoubleInt(double x)
{
string str = x.ToString();
str = str.Replace(",", string.Empty);
int number;
int.TryParse(str, out number);
return number;
}
方法:
int i = MakeDoubleInt(d);
hmmm如何处理像
2.33
这样的值,使其成为233
?如果计算机能乘法…嗯,2.33和233之间的关系是什么?你想保留多少十进制数字?只有两个as(2.33=>233)?当你尝试将2.33
放入double
,你真正得到的是2.330000000000000710542735760100185871124267578125
(即5246693565886628/2**51
)。那你想要什么?如果double
是Math.PI
,您将在哪里截断(如果您使用32位类型的目标类型int
)plus1
。[填充文本。请忽略]如果x
是7E-05
,该怎么办?如果x
是56.789012345
?
static int MakeDoubleInt(double x)
{
return int.Parse(x.ToString().Replace(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator, ""));
}