我的程序将一个点云保存到文件中,每个点云都是Point3D[,]
命名空间中的一个System.Windows.Media.Media3D
。这显示输出文件的一行(葡萄牙语):
-112,644088741971;71,796623005014;NaN (Não é um número)
虽然我希望它是(以便在以后正确解析):
-112,644088741971;71,796623005014;NaN
生成文件的代码块在这里:
var lines = new List<string>();
for (int rows = 0; rows < malha.GetLength(0); rows++) {
for (int cols = 0; cols < malha.GetLength(1); cols++) {
double x = coordenadas_x[cols];
double y = coordenadas_y[rows];
double z;
if ( SomeTest() ) {
z = alglib.rbfcalc2(model, x, y);
} else {
z = double.NaN;
}
var p = new Point3D(x, y, z);
lines.Add(p.ToString());
malha[rows, cols] = p;
}
}
File.WriteAllLines("../../../../dummydata/malha.txt", lines);
从
double.NaN.ToString()
内部调用的Point3D.ToString()
方法似乎包含用括号括起来的“其他说明”,我根本不需要。有没有一种方法可以更改/覆盖此方法,以便仅输出
NaN
,而没有括号部分? 最佳答案
Double.ToString()
使用NumberFormatInfo.CurrentInfo
格式化其数字。最后一个属性引用当前在事件线程上设置的CultureInfo
。默认为用户当前的语言环境。在这种情况下,它是葡萄牙的文化环境。为避免此行为,请使用Double.ToString(IFormatProvider)
重载。在这种情况下,您可以使用CultureInfo.InvariantCulture
。
另外,如果要保留所有其他标记,则可以仅切换NaN符号。默认情况下,全局化信息是只读的。创建一个克隆可以解决这个问题。
System.Globalization.NumberFormatInfo numberFormatInfo =
(System.Globalization.NumberFormatInfo) System.Globalization.NumberFormatInfo.CurrentInfo.Clone();
numberFormatInfo.NaNSymbol = "NaN";
double num = double.NaN;
string numString = System.Number.FormatDouble(num, null, numberFormatInfo);
要在当前线程上进行设置,请创建当前区域性的副本,并在区域性上设置数字格式信息。 Pre .NET 4.5无法为所有线程设置它。创建每个线程后,您必须确保正确的
CultureInfo
。从.NET 4.5开始,CultureInfo.DefaultThreadCurrentCulture
定义了AppDomain
中线程的默认区域性。仅当尚未设置线程的区域性时才考虑使用此设置(请参阅MSDN)。单线程示例:
System.Globalization.CultureInfo myCulture =
(System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
myCulture.NumberFormat.NaNSymbol = "NaN";
System.Threading.Thread.CurrentThread.CurrentCulture = myCulture;
string numString = double.NaN.ToString();
关于c# - 如何在C#中更改NaN字符串表示形式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15301101/