我正在尝试编写一个函数,它基本上将字符串数组转换为字符串数组,其中数组中的所有双精度数都四舍五入为我设置的小数位数。数组中也可以有字符串,这些字符串根本不是双精度值。
string[,] values = new string[1, 3];
values[0, 0] = "hello";
values[0, 1] = "0.123";
values[0, 2] = "0,123";
int decimalPlaces = 2;
double tmp;
string format = "F" + decimalPlaces.ToString();
IFormatProvider provider = CultureInfo.InvariantCulture;
for (int i = 0; i < values.GetLength(0); i++)
{
for (int j = 0; j < values.GetLength(1); j++)
{
if (double.TryParse(values[i, j], out tmp))
{
values[i, j] = tmp.ToString(format, provider);
}
}
}
Console.ReadLine();结果必须是:"hello","0.12","0.12“,但它是"hello”,"123.00","0.12“将以错误的方式处理逗号。有没有人有简单有效的解决方案?
发布于 2021-07-08 15:34:48
如果我只想解析一个带有小数点分隔符的数字,我会使用下面的代码片段:
public bool TryParseDecimal(string value, out decimal result) {
const string your_separator = ",";
var numberFormat = new NumberFormatInfo {
NumberDecimalSeparator = your_separator
};
return decimal.TryParse(value, NumberStyles.AllowDecimalPoint, numberFormat, out result);
}我不认为使用区域性或字符串操作表达了将数字转换为非‘’的意图。小数点。
https://stackoverflow.com/questions/11560465
复制相似问题