简体   繁体   English

C#如何将double转换为int数组

[英]C# how to convert a double an int array

This is my first post on Stack Overflow ever. 这是我有关堆栈溢出的第一篇文章。 If I do it wrong, please correct me: 如果我做错了,请纠正我:

Using C#, I'd like to convert a double to an int array of variable length equal to the total number of digits in the double. 使用C#,我想将一个double转换为一个可变长度的int数组,该数组的长度等于double中的位数。

for example, if I had the number 35.777778, I would want to convert it an int array where 例如,如果我有数字35.777778,我想将其转换为int数组,其中

array[0] = 3
array[1] = 5
array[2] = 7
etc.

I plan to iterate through the array and compare array[i] to array[i + 1]. 我计划遍历数组并将array [i]与array [i + 1]比较。

The double will be the quotient of two variable numbers. 双精度数将是两个变量数的商。 So it may have very few digtis or a lot of digits. 因此,它可能只有很少的数字或很多数字。

So far I have tried to convert it to a string and then to an array of ints. 到目前为止,我已经尝试将其转换为字符串,然后转换为整数数组。 But it crashes at the decimal point. 但是它在小数点崩溃。

Please help me... 请帮我...

This should do it: 应该这样做:

int[] array = 35.777778.ToString().Replace(".", String.Empty)
                                  .Select(c => (int)Char.GetNumericValue(c))
                                  .ToArray();

You could do it the way you were doing (convert to string and then parse each char to an int) and just strip out the decimal point. 您可以按照自己的方式进行操作(转换为字符串,然后将每个char解析为一个int),然后去除小数点。 Like so: 像这样:

var nums = decimalNum.ToString().Replace('.', '').ToCharArray();
int[] numbers = new int[nums.Count];
var x = 0;
foreach (var item in nums)
{
    numbers[x] = Integer.ParseInt(item);
    x++;
}

This obviously isn't the prettiest solution, but it would work. 显然,这不是最漂亮的解决方案,但它可以工作。

Floating point to decimal digit conversion is a hard problem. 浮点数到十进制数字的转换是一个难题。 In .NET, the tool have available is really the double.ToString method which is bloated and especially bad when you want the digits. 在.NET中,可用的工具实际上是double.ToString方法,它method肿且在需要数字时尤其糟糕。 As you see the other answers all have to parse back to integer. 如您所见,所有其他答案都必须解析回整数。

If performance is important there are good double to string conversion algorithms out there that can be modified to fit your needs. 如果性能很重要,那么可以使用一些不错的双字符串转换算法,以适应您的需求。 This one is good: 这个很好:

C# port of google's Grisu conversion Google Grisu转换的C#端口

int[] array = 35.777778.ToString().Where(c => char.IsDigit(c)).Select(c1 => Convert.ToInt32(c1.ToString())).ToArray();

即使double值包含任何字符(例如E-10),此代码也将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM