[英]Converting string to double in C#
I have a long string with double-type values separated by #
- value1#value2#value3#
etc我有一个双类型值的长字符串,由
#
- value1#value2#value3#
等分隔
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?
这里的类型转换有什么问题?
string a = "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]); // correct value
Convert.ToDouble(someArray[i]); // error
}
There are 3 problems.有3个问题。
1) Incorrect decimal separator 1) 小数点分隔符不正确
Different cultures use different decimal separators (namely ,
and .
).不同的文化使用不同的小数点分隔符(即
,
和.
)。
If you replace .
如果更换
.
with ,
it should work as expected: ,
它应该按预期工作:
Console.WriteLine(Convert.ToDouble("52,8725945"));
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 ) eg using double.Parse
:在这种情况下,您可以使用
InvariantCulture
( 什么是不变文化),例如使用double.Parse
:
double.Parse("52.8725945", System.Globalization.CultureInfo.InvariantCulture);
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
.您还应该看看
double.TryParse
,您可以将它与许多选项一起使用,并且检查您的字符串是否是有效的double
尤其有用。
2) You have an incorrect double 2)你的双打不正确
One of your values is incorrect, because it contains two dots:您的值之一不正确,因为它包含两个点:
15.5859949000000662452.23862099999999
3) Your array has an empty value at the end, which is an incorrect double 3)你的数组最后有一个空值,这是一个不正确的双
You can use overloaded Split
which removes empty values:您可以使用重载的
Split
删除空值:
string[] someArray = a.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
Add a class as Public and use it very easily like convertToInt32()添加一个类为 Public 并像 convertToInt32() 一样轻松使用它
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Common
/// </summary>
public static class Common
{
public static double ConvertToDouble(string Value) {
if (Value == null) {
return 0;
}
else {
double OutVal;
double.TryParse(Value, out OutVal);
if (double.IsNaN(OutVal) || double.IsInfinity(OutVal)) {
return 0;
}
return OutVal;
}
}
}
Then Call The Function然后调用函数
double DirectExpense = Common.ConvertToDouble(dr["DrAmount"].ToString());
Most people already tried to answer your questions.大多数人已经尝试回答您的问题。
If you are still debugging, have you thought about using:如果还在调试,有没有想过使用:
Double.TryParse(String, Double);
This will help you in determining what is wrong in each of the string first before you do the actual parsing.这将帮助您在进行实际解析之前首先确定每个字符串中有什么问题。
If you have a culture-related problem, you might consider using:如果您有与文化相关的问题,您可以考虑使用:
Double.TryParse(String, NumberStyles, IFormatProvider, Double);
This http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx has a really good example on how to use them.这个http://msdn.microsoft.com/en-us/library/system.double.tryparse.aspx有一个关于如何使用它们的很好的例子。
If you need a long, Int64.TryParse is also available: http://msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx如果您需要很长的 Int64.TryParse,也可以使用: http : //msdn.microsoft.com/en-us/library/system.int64.tryparse.aspx
Hope that helps.希望有帮助。
private double ConvertToDouble(string s)
{
char systemSeparator = Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator[0];
double result = 0;
try
{
if (s != null)
if (!s.Contains(","))
result = double.Parse(s, CultureInfo.InvariantCulture);
else
result = Convert.ToDouble(s.Replace(".", systemSeparator.ToString()).Replace(",", systemSeparator.ToString()));
}
catch (Exception e)
{
try
{
result = Convert.ToDouble(s);
}
catch
{
try
{
result = Convert.ToDouble(s.Replace(",", ";").Replace(".", ",").Replace(";", "."));
}
catch {
throw new Exception("Wrong string-to-double format");
}
}
}
return result;
}
and successfully passed tests are:并成功通过的测试是:
Debug.Assert(ConvertToDouble("1.000.007") == 1000007.00);
Debug.Assert(ConvertToDouble("1.000.007,00") == 1000007.00);
Debug.Assert(ConvertToDouble("1.000,07") == 1000.07);
Debug.Assert(ConvertToDouble("1,000,007") == 1000007.00);
Debug.Assert(ConvertToDouble("1,000,000.07") == 1000000.07);
Debug.Assert(ConvertToDouble("1,007") == 1.007);
Debug.Assert(ConvertToDouble("1.07") == 1.07);
Debug.Assert(ConvertToDouble("1.007") == 1007.00);
Debug.Assert(ConvertToDouble("1.000.007E-08") == 0.07);
Debug.Assert(ConvertToDouble("1,000,007E-08") == 0.07);
You can try this example out.你可以试试这个例子。 A simple C# progaram to convert string to double
一个简单的 C# 程序将字符串转换为双精度
class Calculations{
protected double length;
protected double height;
protected double width;
public void get_data(){
this.length = Convert.ToDouble(Console.ReadLine());
this.width = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());
}
}
In your string I see: 15.5859949000000662452.23862099999999
which is not a double (it has two decimal points).在您的字符串中,我看到:
15.5859949000000662452.23862099999999
这不是双15.5859949000000662452.23862099999999
数(它有两个小数点)。 Perhaps it's just a legitimate input error?也许这只是一个合法的输入错误?
You may also want to figure out if your last String
will be empty, and account for that situation.您可能还想弄清楚您的最后一个
String
是否为空,并考虑这种情况。
public static double ConvertToDouble(string value)
{
if (value == null) return 0;
double.TryParse(value, out var val);
return double.IsNaN(val) || double.IsInfinity(val) ? 0 : val;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.