问题描述
尝试了 这个问题,它似乎没有给我想要的格式(1.000.000 | 1.234).
Having tried all different solutions from this question, it doesn't seem to give me the wanted format (1.000.000 | 1.234).
我已经试过了:
dataBlock.ValueCell.Value = String.Format("{0:#.##0}", double.Parse(dataBlock.ValueCell.Value)); // 1 234
dataBlock.ValueCell.Value = String.Format("{0:N0}", double.Parse(dataBlock.ValueCell.Value)); // 1 234
dataBlock.ValueCell.Value = String.Format("{0}", double.Parse(dataBlock.ValueCell.Value.ToString("N0"))); // 1 234
//values as I read them from Excel = OLDVALUE
//values as I convert them to the wanted number format = NEWVALUE
//OLDVALUE == 2238,8
//NEWVALUE == 2 239
//OLDVALUE == -5372
//NEWVALUE == -5 372
//OLDVALUE == 3909,6
//NEWVALUE == 3 910
还有其他解决方案吗?
我可以用点代替空格,但这看起来确实是糟糕的代码.
I could replace the space with a dot, but that does seem like bad code.
edit1:我试过了
dataBlock.ValueCell.Value = dataBlock.ValueCell.Value.ToString().Replace(' ', '.');
它给了我相同的输出,为什么字符串格式和替换不起作用?
dataBlock.ValueCell.Value = dataBlock.ValueCell.Value.ToString().Replace(' ', '.');
And it give me the same output, how come the string format and replace don't work?
edit2:添加了 Nikita 的回答 [作品]
edit2: added Nikita's answer [Works]
var doubleValue = double.Parse(dataBlock.ValueCell.Value);
Console.WriteLine("doubleValue = " + doubleValue);
var formattedValue = doubleValue.ToString("N0", new CultureInfo("is-IS"));
Console.WriteLine("formattedValue = " + formattedValue);
dataBlock.ValueCell.Value = formattedValue;
给了我这个输出:
doubleValue = 29300
formattedValue = 29.300
doubleValue = 20300
formattedValue = 20.300
doubleValue = 32360
formattedValue = 32.360
doubleValue = 28300
formattedValue = 28.300
doubleValue = 9000
formattedValue = 9.000
...
edit3:这里是更多缺失"的数据更好地了解情况
edit3: Here is more 'missing' data to get a better view of the situation
推荐答案
添加额外的步骤来验证 double.Parse()
的工作方式.可能会有一些惊喜.其中之一可以是整数值和小数之间的分隔符:、
或 .
Add an extra step to verify how double.Parse()
works. There might some surprises. One of them can be the separation char between integer value and decimals: ,
or .
// step 1: verify your string taken from excel
var cellString = dataBlock.ValueCell.Value.ToString();
// if you have a blank space there, remove it
cellString = cellString.Replace(' ', '');
// step 2: verify your double converted value
var doubleValue = double.Parse(cellString);
Console.WriteLine("doubleValue = " + doubleValue);
// step 3: verify the formatting
var formattedValue = doubleValue.ToString("#.##0");
Console.WriteLine("formattedValue = " + formattedValue);
dataBlock.ValueCell.Value = formattedValue;
查看实际数据后进行后期从单元格中获取的字符串中有一个空格.您可以通过添加另一个步骤来验证这一点
Later edit after viewing actual data:You have a blank space in the string you take from the cell. You can verify this by adding another step
这篇关于C# String.Format() - 数字格式不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!