A string.Format question (.NET) - c#

Can someone elaborate on the following format string? I don't completely realize the meaning.
String.Format("{0:#,0.##}", money);
Thanks.

I don't have my development system with me so I can't verify what I'm about to say, but here's my interpretation:
The format portion is "#,0.##". I'm thinking the "#,0" portion specifies a comma should separate thousands (e.g. 1,000,000). And the ".##" is specifying the number of digits after the decimal. I would have thought you'd need ".00" to force two digits (which would be normal for currency). But I would expect what you have to at least cause rounding to two digits after the decimal.
Did you try it?

it means that the money have thousand separator(,) and if in decimal values it will be rounded to two digits after decimal, and if there is only decimal values(.256) it will be (0.27)
decimal money=12341257 //output= 12,341,257
decimal money=1257 //output= 1,257
decimal money=1257.25 //output= 1,257.25
decimal money=1257.2468 //output= 1,257.25
decimal money=.50 //output= 0.50
decimal money=.759 //output= 0.76
Explanation:
"{0:#,0.##}"
#,0 //means that , as thousand seperator
0.## //means that 0 is placed before if only decimal values as .56 to 0.56
0.## //means if contains decimal then only display 2 digits after decimal
0.00 //means 2 digits after decimal must be displayed whether or not money contains decimal value

I believe it is a currency format with a thousands separator and showing only the first 2 places after the decimal if decimal values are included.
Good overview of custom format strings here:
http://blog.stevex.net/string-formatting-in-csharp/
This link includes more details including a description of a more liberal form of the thousands separator with the "," char:
http://msdn.microsoft.com/en-us/library/0c899ak8%28v=vs.71%29.aspx

Basically, this set the formatting to have a thousands separator and 2 decimal digits. According to Microsoft documentation, numbers will be rounded to the correct decimal places.
This is a good resource for custom numeric format strings :
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Related

C# Round Scientific Notation Value

I have a small double value that is formatted in scientific notation. When I display the value it is displayed in the format 1.34423E-12 with 5 digits after the decimal. I would like to round this value so that it displays like 1.344E-12.
Is there a built in way to round a scientific notation value to x number of decimals?
Use a format string like
double d = 1.34423e-12;
string formattedValue = d.ToString("E3");
Here "E" means to use scientific notation (with capital "E", use "e" if you want a small one...) and 3 stands for three digits after the decimal point.
You can look at Standard numeric format strings at MSDN to see other options. The documentation for the String.Format method also contains useful information about formatting values.
EDIT
If you want more flexibility, you can use Custom numeric Format Strings. Using these you can e.g. also specify the number of digits used for the exponent like
d.ToString("0.000E0"); // -> Results in "13.344E-12" instead of "13.344E-012"
d.ToString("0.000E0000"); // -> "13.344E-0012"

How to convert a string containing an exponential number to decimal and back to string

I'm converting code between delphi and c#.
Values are stored as strings in a text file from the delphi app. An example of the stored value is : '4.42615029219009E-5'
Now in my c# app I need to read in that string value and then later have the capability to write out the value again. Initially I used code similar to:
string stringField = "4.42615029219009E-5";
double someMoneyVar = Convert.ToDouble(stringField)
later if I need to recreate the text file with the value of someMoneyVar then using a simple:
string.Format("{0}", someMoneyVar)
would output:
4.42615029219009E-05 // note the 0
Lastly, I read that it is better to store money as decimals in c#. I've tried to convert the string value to a decimal using decimal.Parse(someMoneyVar, NumberStyles.Any) , however the formatting is lost.
I need the data to be output exactly as it was input.
Note, the value of someMoneyVar may not always contain an exponential part. e.g. 0.0428860331919443. If there is no exponential part to the value of someMoneyVar then the value is written correctly to the text file.
Update:
Digging into delphi's FloatToStr function and help files (which is what stores the value in the text file) i came with the following:
The resulting string uses fixed point format if the number of digits
to the left of the decimal point in the value is less than or equal
to the specified precision, and if the value is greater than or equal
to 0.00001 (Edit: this should be 0.0001. There is an error in the delphi documentation). Otherwise the resulting string uses scientific format,
and the Digits parameter specifies the minimum number of digits in
the exponent (between 0 and 4).
...
If the section for positive values is empty, or if the entire format
string is empty, the value is formatted using general floating-point
formatting with 15 significant digits, corresponding to a call to
FloatToStrF with the ffGeneral format. General floating-point
formatting is also used if the value has more than 18 digits to the
left of the decimal point and the format string does not specify
scientific notation.
So bearing in mind that the FloatToStr function does a call to FloatToStrF uses 15 significant (precision) digits and a 0 as the minumum number of digits hence we end up with
4.42615029219009E-5
if the digits was 2 then the number would be displayed as
4.42615029219009E-05
According to the MSDN http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#GFormatString
using the general format specifier, the precision of double is 15 and decimal is 29
Fixed-point notation is used if the exponent that would result from
expressing the number in scientific notation is greater than -5 and
less than the precision specifier; otherwise, scientific notation is
used. The result contains a decimal point if required, and trailing
zeros after the decimal point are omitted. If the precision specifier
is present and the number of significant digits in the result exceeds
the specified precision, the excess trailing digits are removed by
rounding.
However, if the number is a Decimal and the precision specifier is
omitted, fixed-point notation is always used and trailing zeros are
preserved.
If scientific notation is used, the exponent in the result is prefixed
with "E" if the format specifier is "G", or "e" if the format
specifier is "g". The exponent contains a minimum of two digits. This
differs from the format for scientific notation that is produced by
the exponential format specifier, which includes a minimum of three
digits in the exponent.
The result string is affected by the formatting information of the
current NumberFormatInfo object. The following table lists the
NumberFormatInfo properties that control the formatting of the result
string.
One can easily set the precision e.g. mydecimal.toString("G15") however i still haven't found a way to set the number of digits after the 'E' sign as easily as in the delphi FloatToStrF function
To convert strings to numbers, as you already figured out, you just use a double.
I'd try a different conversion though:
double myNum = double.Parse("<yournumber>", NumberStyles.AllowExponent | NumberStyles.Float, CultureInfo.InvariantCulture);
AllowExponent and Float should keep the notation, and InvariantCulture takes care of the decimal divider (which might not be a dot depending on the locale).
You can output scientific notation numbers via string.Format(), like this:
double num = 1234.5678; // 1.2345678e+03
string.Format("{0:e}", num); // should output "1.2345678E+03"
If you have to distinguish between numbers with and without the "E+xx" part, you'll have to search for it before converting the string to double, and a full snippet (WARNING: not tested!) could look like:
string myString = ReadNumberFromFile(); // Just a placeholder method
double myNum = double.Parse(myString, NumberStyles.AllowExponent | NumberStyles.Float, CultureInfo.InvariantCulture);
string output = string.Empty; //this will be the "converted-back number" container
if (myString.IndexOf("e", StringComparison.OrdinalIgnoreCase) >= 0)
{
//Number contains the exponent
output = string.Format("{0:e}", num); // exponential notation 'xxxExx' casing of 'e' changes the casing of the 'e' in the string
}
else
{
//TODO: Number does NOT contain the exponent
output = string.Format("{0:f}", num); // fixed-point notation in the form 'xxxx.xxx'
}
The point here is that, as far as number go, being with or without an exponent doesn't make any difference whatsoever, it's just a matter of representation (and it makes little sense to distinguish between them: it's really the same thing).

How To Convert a Decimal From 123.45 into 0000000012345 using C#

I have a requirement in doing some conversion work to send over a decimal field into a zero filled string.
I need to turn 1234.56 into 000000000123456
I know I can multiply by 100 to get rid of the decimal (not my favorite thing to do), but then how can i format it to match the requirement?
I'm assuming there's some kind of built in Format method, i just can't find it.
Thanks.
I'd try this: How to: Pad a Number with Leading Zeros
You can pad an integer with leading zeros by using the "D" standard
numeric format string together with a precision specifier. You can pad
both integer and floating-point numbers with leading zeros by using a
custom numeric format string. This topic shows how to use both methods
to pad a number with leading zeros.
This will do it:
string.Format( "{0:D15}", 123456 );
You should consult the documentation for string.Format.
Based on the documentation from http://msdn.microsoft.com/en-us/library/0c899ak8.aspx You could do it by using the following format:
Decimal value = new Decimal(1234.56);
Console.WriteLine("I need to turn {0} into {1}", value, value.ToString("000000000000000"));
Regards,
herber

how can I remove zeros from exponent notation

I'm using exponential formatting to format a decimal number in C#.
For example if the number is
0.0001234567
Formatting with
(0.0000123456).ToString("E4");
Shows
1.2345E-004
How can I remove leading zero from exponent so it read as below?
1.2345E-4
Quoting MSDN:
The case of the format specifier indicates whether to prefix the exponent with an "E" or an "e". The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required.
This is with the standard number specifier.
However, with the custom number format, you can set the number of 0's:
987654 ("#0.0e0") -> 98.8e4
For your case, it's
(0.0000123456).ToString("#0.0E0"); //12.3E-6
Edit after BobSort comment
If you need scientific notation, you can specify that you need only one digit before decimal with the following:
(0.0000123456).ToString("0.00#E0"); //1.23E-5
Assuming you need to always show 4 digits after decimal point, try
"0.0000E+0"
so it will show
(0.0000123456).ToString("0.0000E+0"); //1.2345E-5
(0.0000120000).ToString("0.#E+0"); //1.2000E-5
if you don't need to show 4 digits after decimal points use
"0.#E+0"
so it will show
(0.0000123456).ToString("0.#E+0"); //1.2E-5
(0.0000120000).ToString("0.#E+0"); //1.2E-5

How do I format a double to a string and only show decimal digits when necessary?

I have code like:
lblFranshizShowInvwNoskhehEdit.Text = string.Format("{0:n}",
(double)(int.Parse(drDarman["FranshizDarsad"].ToString()) *
Convert.ToInt64(RadNumerictxtPayInvwNoskhehEdit.Text)) / 100);
But {0:n0} string format forces the label's text to not have decimal digits and {0:n} string format forces the label's text to have 2 decimal digits (default).
In my scenario I just want decimal digits when necessary / without rounding them / how can I do that?
You can just do:
string.Format("{0}", yourDouble);
It will include only digits when necessary.
If you want other examples of formatting doubles to string check out this link.
EDIT: Based on your comment you want the , seperator so you could do:
string.Format("{0:0,0.########}", yourDouble);
Just put as many # for the max number of decimal places you want to show. It will only show the digits when necessary but up to the maximum digits based on how many # you include in the format. The # means only show a digit if necessary so if you give a number like 123 with no decimal, it will display as 1,234 but if you give it 1234.456, it will display as 1,234.456. If you go beyond the max digits you specified they will be rounded.
EDIT: To fix your double zero scenario just change it to:
string.Format("{0:#,0.########}", yourDouble);
That should work perfectly now :)
this is mine :
string.Format("{0:n2}", double);

Categories