Reputation: 3747
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.
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
Upvotes: 1
Views: 1432
Reputation: 2151
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
Upvotes: 1