在 C# 中将字符串转换为双精度 [英] Converting string to double in C#

查看:22
本文介绍了在 C# 中将字符串转换为双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个长字符串,其中包含由 # -value1#value2#value3# 等分隔的双类型值

I have a long string with double-type values separated by # -value1#value2#value3# etc

我将它拆分为字符串表.然后,我想将此表中的每个元素转换为双精度类型,但出现错误.这里的类型转换有什么问题?

I splitted it to string table. Then, I want to convert every single element from this table to double type and I get an error. What is wrong with type-conversion here?

<代码>字符串= 52.8725945#18.69872650000002#50.9028073#14.971600200000012#51.260062#15.5859949000000662452.23862099999999#19.372202799999250800000045#51.7808372#19.474096499999973#";string[] someArray = a.Split(new char[] { '#' });for (int i = 0; i < someArray.Length; i++){Console.WriteLine(someArray[i]);//正确的值Convert.ToDouble(someArray[i]);//错误}

推荐答案

有3个问题.

1) 小数点分隔符不正确

不同的文化使用不同的小数分隔符(即.).

Different cultures use different decimal separators (namely , and .).

如果将 . 替换为 应该可以正常工作:

If you replace . with , it should work as expected:

Console.WriteLine(Convert.ToDouble("52,8725945"));

您可以使用将文化作为第二个参数的重载方法解析您的双打.在这种情况下,您可以使用 InvariantCulture(什么是不变文化a>) 例如使用 double.Parse:

You can parse your doubles using overloaded method which takes culture as a second parameter. In this case you can use InvariantCulture (What is the invariant culture) e.g. using double.Parse:

double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);

您还应该看看 double.TryParse,您可以将它与许多选项一起使用,并且检查您的字符串是否是有效的 double 尤其有用.

You should also take a look at double.TryParse, you can use it with many options and it is especially useful to check wheter or not your string is a valid double.

2) 你的替身不正确

您的某个值不正确,因为它包含两个点:

One of your values is incorrect, because it contains two dots:

15.5859949000000662452.23862099999999

3) 你的数组末尾有一个空值,这是一个不正确的双精度数

您可以使用重载的 Split 来删除空值:

You can use overloaded Split which removes empty values:

string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);

这篇关于在 C# 中将字符串转换为双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆