如何获取字符串中表示的double的整数部分?

时间:2015-04-07 18:43:09

标签: c#

我有一个double值表示为字符串。我想只得到数字的整数部分作为字符串

我该怎么做?例如,使用此字符串:

string str ="123.0000";

我想最终得到这个字符串

 string result ="123";

5 个答案:

答案 0 :(得分:3)

如果你不需要舍入,你可以将它解析为double,然后将其转换为int。

int i = (int)double.Parse("123.000");

答案 1 :(得分:3)

您可以尝试这样的事情:

int integralPart = (int)Double.Parse(str);

首先解析字符串并创建一个double,然后将double转换为整数。

另一种方法是,根据点分割字符串。

var parts = str.Split('.');

然后,如果你想要整数部分的字符串表示,只需得到数组中的第一项:

parts[0]

如果你想创建一个整数,只需解析后者:

int integralPart = int.Parse(parts[0]);

对于更主动的编程风格,最好使用TryParsedouble的{​​{1}}方法,以便处理任何异常。

例如:

int

答案 2 :(得分:2)

看到您希望将结果作为字符串,您只需抓住chars,直到遇到非数字:

string str = "123.0000";
str = new string(str.TakeWhile(char.IsDigit).ToArray());

答案 3 :(得分:1)

你可以尝试使用它:

int myInt = (int)Double.Parse(string);

答案 4 :(得分:0)

在我看来,你应该使用.NET内置函数来使你的代码尽可能明确。

您应解析数字(使用Decimal.Parse或Decimal.TryParse),然后使用Math.Floor或Math.Truncate函数。您想要使用哪一个取决于您想要处理负值的方式。

参考: https://msdn.microsoft.com/pl-pl/library/7d101hyf(v=vs.110).aspx https://msdn.microsoft.com/pl-pl/library/e0b5f0xb(v=vs.110).aspx

相关功能: https://msdn.microsoft.com/pl-pl/library/system.math.round(v=vs.110).aspx https://msdn.microsoft.com/pl-pl/library/zx4t0t48(v=vs.110).aspx