I am looking to format a value in a datagridview.
These values are a string containing a decimal number. (Like "3000"
I want to display it with a thousand separator (space), like this: "3,000".
I know it can be done by assigning format of defaultcellstyle using format like "N2" for example, this works with decimal column type but
I'm using a string column type in my datagridview to handle some exception(displaying "-" instead of "0" to simplify users view)
I tried differents cell style format and nothing changed in the display.
do i need to change the column type of my datagridview or it can be done without too much code ?
Thanks for all reply,
Tristan
i just made it working as i expected. i did the commented things first and it just showed errors, so i tried the second way (simpliest) that is not commented.
string value = cell.Value.ToString();
//NumberFormatInfo nfi =(NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
//nfi.NumberGroupSeparator = " ";
//string formatted = double.Parse(value).ToString("n", nfi);
//cell.Value = formatted.Replace(".00","");// 12 345.00
string formatted = double.Parse(value).ToString("# ### ###");
cell.Value = formatted;
Related
I have an issue where I need to add two numeric strings "$1,234.56" and "$9,876.54" and get a string "$11,111.10"
I can convert the strings to numbers, perform the addition, but I don't know of a good way to preserve the formatting when I ToString() the result. I can add a couple of if statements along the lines: does the input have dollar sign, decimal point, percent sign and construct the format string accordingly, but this is clunky and will fail if we ever need to support more than one number format.
Does anyone know how to add numeric strings and preserve formatting?
EDIT: To answer the questions. The format of all strings being added at a given time is the same ie: I don't need to worry about adding $ and £ (in fact £ is not currently supported), However, there are several possible formats that are currently supported and more may be added in the future:
$1,234.00; $1,234; 1234; 1,234; 1,234.00; 1234%; 1,234%; 1,234.00%
I would suggest using the first numeric string as a template and create a number format from it:
var posshalves = firstNumericString.Split('.');
var fmthalves = new string[2] { posshalves[0], (posshalves.Length < 2 ? "" : "."+posshalves[1])};
var intfmt = Regex.Replace(fmthalves[0], #"[0-9]", "#");
intfmt = Regex.Replace(intfmt, #"#+", "#");
var decfmt = Regex.Replace(fmthalves[1], "[0-9]", "0");
var format = $"{intfmt}{decfmt}";
I want to convert date to string in excel, i have similiar problem to this :
Convert date field into text in Excel
But I need to implement this in C# project, any idea how to achieve that ?
I had numbers in format like this : "1-2".
I also get strange number like 40530 after formating whole excel file to text, I think that's the number of days from year 1900.
EDIT:
I didn't mention that I'm reading data from .xml file, then fill excel file with this data, I had some columns that I fill with text like "1-2", but when I open excel it's shows as 2 January (excel changes it to date automatically).
SOLUTION
Maybe someone will use it:
if (value != null)
{
if (value.Contains("-") && value.Length == 3) // cause my value = "1-2"
{
value = "'" + value; // addin ' to value
}
} //now value ="'1-2"
Where value is my cell that I'm writing to excel. The " ' " sign will guarantee that the value "1-2" will be displayed as text, not as date.
Hi I have this code in my .cs file and the output is 100449.00 but I want it to format into money like 100,449.00. This is my code to show the value in the label.
billing.Text = "$" + ds.Tables[0].Rows[0]["Billing"].ToString();
billing.Text = "$" + ds.Tables[0].Rows[0]["Billing"].ToString("N");
Per this.
Edit: what's returned is an object which you need to cast to a decimal. Try:
((decimal)ds.Tables[0].Rows[0]["Billing"]).ToString("N");
billing.Text = ds.Tables[0].Rows[0]["Billing"].ToString("c");
Coming from a DataTable requires us to convert to a non-nullable type before we format as text.
We actually have a few different ways to do the formatting. Your post has a hardcoded dollar sign preceding the value, in which case we can use either the F2 or N2 format strings to give us a decimal point with 2 places to the right and append that to the dollar sign you have in there:
billing.Text = "$" + ((decimal)ds.Tables[0].Rows[0]["Billing"]).ToString("F2");
// 123456.7890 will display as $123456.78
billing.Text = "$" + ((decimal)ds.Tables[0].Rows[0]["Billing"]).ToString("N2");
// 123456.7890 will display as $123,456.78
Another option is to use the C format which will add in the cultural specific currency symbol and numeric format (decimal points, commas) for us
billing.Text = ((decimal)ds.Tables[0].Rows[0]["Billing"]).ToString("C");
// 123456.7890 will display as
// $123,456.78 en-US
// 123 456.78€ fr-FR
// you could also add a second overload to the ToString to specify
I'm trying to create an Excel spreadsheet in my web application using a tab-delimited text file as the data source. The code that loads my data looks like this:
// Load the data into the cells
Int32 rowIdx = 1;
foreach (String line in tab.Lines)
{
String[] cellTexts = line.Split(TAB);
Int32 colIdx = 1;
foreach (String cellText in cellTexts)
{
sheet.Cells[rowIdx, colIdx].Value = cellText;
colIdx++;
}
rowIdx++;
}
That seems to work fine. Later, however, I add a NumberFormat of "mm/dd/yyyy" to the cells:
range.Style.Numberformat.Format = "mm/dd/yyyy";
However, this doesn't change the display of the data in the cells. (The dates look like 5/1/15 or 12/31/15 in the original text file, and remain that way after the format is applied.
I am pretty sure that this because I've put a text value into the cell. (While it looks like a date, it's still just a string of characters.) But from my reading, I need to put a double into the cell to meet Excel's expectation that dates are stored as a double. Because the cell contains a string and not a double, the format string isn't applied, leaving the original, unformatted text.
I want to add some code to
Check the type of data in each cell in the range to which I apply a
date format.
If it's not a double, attempt to convert it to a date.
If the date conversion is successful, then convert the .NET date to an OADate and put it back into the cell.
My question is: Is this the best (or at least a reasonable) approach, and if so, how do I do that?
This code doesn't work:
foreach (OfficeOpenXml.ExcelRangeBase oneCell in range)
{
if (typeof(oneCell.Value) == "System.String")
{
// date manipulations here
}
}
The red line appears under oneCell in the typeof(oneCell.Value) call with the message "The type or namespace 'oneCell' could not be found. (Are you missing a using directive or an assembly reference?)"
Note that I can't know in advance where the date fields will be because both the data and the cell formats are provided from an external source. (The external cell formats do indicate when the format being applied is for a date format as opposed to a regular number format or a string.)
As #mason suggested, I'm posting the code I used to get around this problem.
(I didn't get an answer to my original question, which is how to iterate cells in a range and check the data type of each cell's content, but with this solution, I no longer need to do that.)
Instead, I modified the loop that loads the data from the tab-delimited text file to use some TryParse() calls to detect dates, numbers, or regular text data, and then load the appropriately typed data into the cell. Note how it checks for a leading single quote character to suppress the data typing if the cell is actually text, but looks like a number or a date:
// Load the data into the cells
Int32 rowIdx = 1;
foreach (String line in tab.Lines)
{
String[] cellTexts = line.Split(TAB);
Int32 colIdx = 1;
foreach (String cellText in cellTexts)
{
DateTime dateValue;
Double doubleValue;
if(cellText.StartsWith("'"))
{
sheet.Cells[rowIdx, colIdx].Value = cellText.Substring(1);
}
else if(DateTime.TryParse(cellText,out dateValue))
{
sheet.Cells[rowIdx, colIdx].Value = dateValue;
}
else if (Double.TryParse(cellText, out doubleValue))
{
sheet.Cells[rowIdx, colIdx].Value = doubleValue;
}
else
{
sheet.Cells[rowIdx, colIdx].Value = cellText;
}
colIdx++;
}
rowIdx++;
}
With the data typed appropriately in the cells, the formats have the desired effect.
Background: We have a system that receives data from another backend system. We handle the displaying of that data, and we have our own XML templates to control how certain things are displayed (i.e. we have our own column templates to dictate what the column headers are, etc.) One thing we would like to support is the ability to provide a mask for these column templates that would apply to the values coming from the backend. Below is a scenario that I'm having trouble with.
Problem: I can't seem to get a simple string format working. I'd like to format a STRING value of four digits (i.e. "1444") in a time format (i.e. "14:44"). I've tried:
String.Format("{0:00:00}", "1444")
Note the importance of the input being a STRING. If I supply an int value, the format will work. The reason I cannot use this is because all the data we receive from the backend is in string format, and we'd like for this to be generic (so casting isn't really an option).
By generic, I mean I'd like to specify a mask in our own XML templates, something like:
<MyColumnTemplate Id="MyColumn" Mask="00:00" />
and to use that mask in a string format call for string values? If the mask fails, we could just simply return the original value (as the String.Format() method already does by default).
Edit: To help clarify, here is a simplified version of what I'd like to be able to do in code:
string inputValue = "1444";
string maskValueFromXml = "00:00";
string mask = "{0:" + maskValueFromXml + "}";
string myDesiredEndResult = String.Format(mask, inputValue);
The thing is you are working string to string,since you ask for time and phone number they are all numbers then try this trick(if we can call it that :)):
string result = string.Format("{0:00:00}", int.Parse("1444"));
For phone number:
string result = string.Format("{0:000-000-0000}", int.Parse("1234560789"));
You can even place your desired masks in a dictionary for example and do this:
Dictionary<string, string> masks = new Dictionary<string, string>();
masks.Add("Phone", "{0:000-000-0000}");
masks.Add("Time", "{0:00:00}");
string test = "1234560789";
string result = string.Format(masks["Phone"], int.Parse(test));
Try with DateTime.TryParseExact, e.g:
DateTime dateEntered;
string input = "1444";
if (DateTime.TryParseExact(input, "HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateEntered))
{
MessageBox.Show(dateEntered.ToString());
}
else
{
MessageBox.Show("You need to enter valid 24hr time");
}
After that, you can use string.Format, predefined formats on MSDN.