Formatting a number string to add commas - c# - c#

I know this question has been answered many times before however, I'm convinced the code I have is correct but isn't working correctly.
string total = ds.Tables[0].Rows[0][0].ToString();
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;
This code isn't adding the commas into my value like it desire it to.
Can anyone see why?

When you put
string total = ds.Tables[0].Rows[0][0].ToString();
it means implicit G ("General") format string
string total = ds.Tables[0].Rows[0][0].ToString("G");
Do not format prematurely:
var total = ds.Tables[0].Rows[0][0]; // Value from table
string test = string.Format("{0:N}", total); // Format total with "N" format string

Your code is trying to format a string. If the DataTable contains a number you can pass the format specifier to ToString(), eg
var test=ds.Tables[0].Rows[0][0].ToString("N");
Or store the contents in a local variable and use String.Format :
var total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);
If the datatable contains a string though, you'd have to parse it to a numeric type first

You have to use the string.Format with a number type, instead of string. In this case, the variable total is a string, it must be a number.

There are 8 overloads for the Strig.Format method. You are using this specific one: Format(String, Object) in which you pass a String value as argument of the second parameter. This is because you are using a string variable (total) to assign the value from the dataset in:
string total = ds.Tables[0].Rows[0][0].ToString();
Besides you are using .ToString() to retrieve it as a String.
If you are using SQL Server as data source to your ds dataset and you are certain about the SQL data type then you can assign that value directly to a variable with the corresponding C# type. To put it in a different way, SQL data types are mapped to C# data types.
If you are not sure about the C# data type of ds.Tables[0].Rows[0][0] then you could simply do the following:
Object total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;
And this way you literally use the Format(String, Object) overload of String.Format.

Related

C# - Returning a single value (any datatype) from a DataTable as a string

I've loaded a table from excel in C# using the ExcelDataReader package, however I'm struggling to write a method which returns the value of a cell as a string, based on the row number and column name.
I have a solution for a method that works if there are just strings in the DataTable...
public string ReadData(int rowNum, string columnName)
{
DataRow row = table.Rows[rowNum];
string value = row.Field<string>(columnName);
return value;
}
(the DataTable variable 'table' is loaded elsewhere)
..however I would like also like to be able to return numbers and dates (as strings).
I feel I might need to edit this part somehow...
string value = row.Field<string>(columnName);
But I don't know how to make it so it pulls back whatever value and type is in that field and returns a string.
Many thanks!
You can simply use the by-name-indexer and call ToString():
string value = row[columnName].ToString();
You probably should check for null values:
string value = (row[columnName] ?? string.Empty).ToString();
You could use, DataRow name-indexer returns an object on which we can call .ToString() to convert it to string.
return row[columnname].ToString();
Use
string value = Convert.ToString(row[columnName]);
Using Convert.ToString() is preferrable because it does not only check for null but also for DBNull, which is the value of the column when accessing a real database where the column has no content.
In C# 6.0:
return row[columnName]?.ToString();

formatting decimals using string format

public static string PadZero(this double number, int decimalPlaces)
{
var requiredFormat = "0." + "".PadRight(decimalPlaces, '0');
var something = $"{number:requiredFormat}";
return number.IsNotZero() ? something: string.Empty;
}
This is a helper function to pad zeros to a double number, user can pass the number of zeros that is required to be padded through decimalPlaces.
Above function fails my unit tests, output received is {requiredFormat} in all test cases.
I have just replaced: var something = $"{number:0.00}"; with a generic variable requiredFormat that can handle any number of zero padding.
There are two problems with your example. The first is that the value of something is not going to produce a string that can be used to format a number. The second is that you are not using something to perform a number format by using string.format.
So first off, the statement:
var something = $"{number:requiredFormat}";
is not going to give you the result that you want, which would be a string that looks something like:
{0:0.0000}
Try changing the code to read:
var something = $"{{0:{requiredFormat}}}";
If you do Console.WriteLine(something) after that statement executes you can inspect the value of something to make sure it is what you are looking for.
After that, change this line:
return number.IsNotZero() ? something: string.Empty;
to read:
return number.IsNotZero() ? string.Format(something, number) : string.Empty;
Even with Interpolated Strings, you have to build the variable format and apply it in two separate steps.
Hope that helps.

Create a custom string c#

I have a numeric id of integer type. I want to add that integer type value to 00000 and concatenate it with string type variable.Assume my integer variable value is 1. After adding the variable it should look like 00001. And I want to concatenate with a string like "Added" and then convert whole thing to a string variable. like this "Added00001". As another example if my integer value is 111 it should look like "Added00111" at the end. Another example integer variable = 1234. Final string should be "Added01234". How to do it...? An example of how to do it.. or Any tutorial how to do such a thing would be really great. Thanks in advance.
You should use the short form format specifier of the ToString method. In the example below, D5 indicates that the integer 111 should be converted to a string with padded zeros to a length of 5 digits, e.g. 00111.
int i = 111;
string s = "Added";
var s = s + i.ToString("D5");
//s = "Added00111"

How to change display format of long variable?

I have a variable of type Long i.e.
long quantity=1000;
I want to display it like 1,000 in Grid (Must need commas)
How do i achieve this?
I am using a Telerik Grid and I am binding the data as follows:
columns.Bound(tempProductList => tempProductList.tempProductListQuantity) .Title("Quantity")
Here you have a list of all the standard numeric formats. I think "N" is the one you want.
long l = 1234;
string s = l.ToString("N0"); //gives "1,234"
The "0" after the format specifier is the number of desired decimal places (usually 2 by default).
Note that this version is culture-sensitive, i.e., in my country, we use dots (".") as thousand separators, so the actual returned value will be "1.234" instead of the "1,234". If this is desired behaviour, just leave it as is, but if you need to use commas always, then you should specify a culture as a parameter to the ToString method, like
l.ToString("N0", CultureInfo.InvariantCulture); //always return "1,234"
You could create a Custom Culture that will allow you to specify the thousand separator.
From this article:
//Create first the format provider the String.Format
//will use to format our string
CultureInfo cultureToUse = new CultureInfo("fi-FI");
Console.WriteLine("Using the following CultureInfor " +
cultureToUse.Name);
//Now practice some decimal numbers
//Here we override the culture specific formattings
cultureToUse.NumberFormat.CurrencyDecimalDigits = 3;
cultureToUse.NumberFormat.NumberDecimalDigits = 3;
cultureToUse.NumberFormat.NumberGroupSeparator = " ";
cultureToUse.NumberFormat.CurrencySymbol = "euro";
cultureToUse.NumberFormat.NumberDecimalSeparator = ",";
Next you would need to use this culture when formatting the numbers.
You could do the formattin gby hand but you could also assign the culture to the Current(UI)Culture property of the current thread.
If you want to consider the international point of view, there will not be always commas before the decimal part. ToString function will give you what you want.
(1000.0).ToString("N",new CultureInfo("en-US")) = 1,000.00
(1000.0).ToString("N",new CultureInfo("is-IS")) = 1.000,00

Good way to translate numeric to string, with decimal point removed?

I have to deal with a numeric value (coming from a SQL Server 2005 numeric column) which I need to convert to a string, with the caveat that the decimal point has to be removed. The data itself is accessible in C# via a DataTable/DataRow.
For example, if the SQL Server column reads 12345.678, the string should be "12345678" when all is said and done. Would it be possible to point me toward a good approach for this? Maybe there's a .Net conversion method that does this, I'm not sure.
Thanks!
There are several possible approaches. You could convert it to a string using a specific culture so that you are sure that the period is used as decimal separator, then remove the period:
string s = num.ToString(CultureInfo.InvariantCulture).Replace(".", String.Empty);
You could use a more numeric approach to multiply the valye by 10 until there are no decimals:
while (num != Math.Floor(num)) num *= 10.0;
string s = ((int)num).ToString();
what about something like
var numberWithPoint = dbGetNumber();
string numberWithOutPoint = numberWithPoint.ToString().Replace(".", string.Empty);
it's quick and dirty, but it get the job done fairly simply.
you can do it in c# like:
var myNum = 12345.678;
var myString = myNum.ToString().Replace(".","");
in sql server, you can do it like:
SELECT REPLACE( cast(myCol as varchar), '.', '') as FormattedNumber
FROM ...
What about:
// using System.Globalization;
SqlCommand cm = new SqlCommand("SELECT 12345.678 as decimal");
// ...
SqlDataReader dr = cm.ExecuteReader();
if(dr.Read())
{
string value = dr.GetValue(0).ToString()
.Replace(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator, "")
}
but usually when it comes from sql server, you should not convert it first to a string than to integer / double but convert it directly from object in row["column1"] to needed value, this will save you troubles handling cultures and improve performance a bit
A straightforward method is to use
string result = original.Replace(".", "")
There might be a faster method, but if this isn't in a tight inner loop, Replace should work fine.
EDIT: Fixed code example, plus:
To address culture concerns, one might use NumberFormatInfo.NumberDecimalSeparator to determine the currently defined decimal separator.
string result = Regex.Replace(original, "[^0-9]", "");

Categories

Resources