C# String.Format() - number format doesn't work

≯℡__Kan透↙ 提交于 2019-12-24 11:28:30

问题


Having tried all different solutions from this question, it doesn't seem to give me the wanted format (1.000.000 | 1.234).

I Have tried this:

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

Any other solutions?

I could replace the space with a dot, but that does seem like bad code.

Edits

edit1: I tried this

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: 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;

gave me this output:

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: Here is more 'missing' data to get a better view of the situation


回答1:


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



来源:https://stackoverflow.com/questions/32580818/c-sharp-string-format-number-format-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!