String.Format is not working properly - c#

I have below code :
private string Do2Decimal(string value)
{
return String.Format("{0:0.##}", value);
}
Here I am passing string value as 16.32222.
What I know is, above code should format my value to 16.32.
But it is showing output value as 16.32222.
What mistake I am doing here??
Update :
I have values in string format that is : "16.32222".
Sorry forgot to mention before.

Because you are passing it a string value. The formatting would work for floating point numbers / decimals. Just parse the number to either decimal / double type depending on your requirement like:
String.Format("{0:0.##}", decimal.Parse(value));
You can also use decimal.TryParse (or TryParse) family method for safer parsing. You can also modify your method to receive decimal/double type parameter and then apply the formatting. It would convey a better intent, IMO.
If your string has . as NumberDecimalSeparator and your culture doesn't support . as NumberDecimalSeparator then you can pass CultureInfo.InvariantCulture while parsing like:
string value = "16.322222";
string formattedString = String.Format("{0:0.##}", decimal.Parse(value, CultureInfo.InvariantCulture));

Try this
String.Format("{0:0.00}", decimal.Parse(value));
to get two degit value after point.

Related

How to convert string to decimal with 3 decimal places?

string num = 23.6;
I want to know how can I convert it into decimal with 3 decimal places
like
decimal nn = 23.600
Is there any method?
I try my best..
First of all your string num = 23.6; won't even compile. You need to use double quotes with your strings like string num = "23.6";
If you wanna get this as a decimal, you need to parse it first with a IFormatProvider that have . as a NumberDecimalSeparator like InvariantCulture(if your CurrentCulture uses . already, you don't have to pass second paramter);
decimal nn = decimal.Parse(num, CultureInfo.InvariantCulture);
Now we have a 23.6 as a decimal value. But as a value, 23.6, 23.60, 23.600 and 23.60000000000 are totally same, right? No matter which one you parse it to decimal, you will get the same value as a 23.6M in debugger. Looks like these are not true. See Jon Skeet comments on this answer and his "Keeping zeroes" section on Decimal floating point in .NET article.
Now what? Yes, we need to get it's textual representation as 23.600. Since we need only decimal separator in a textual representation, The "F" Format Specifier will fits out needs.
string str = nn.ToString("F3", CultureInfo.InvariantCulture); // 23.600
There are two different concepts here.
Value
View
you can have a value of 1 and view it like 1.0 or 1.0000 or +000001.00.
you have string 23.6. you can convert it to decimal using var d = decimal.Parse("23.6")
now you have a value equals to 23.6 you can view it like 23.600 by using d.ToString("F3")
you can read more about formatting decimal values
the thing that works for me in my case is num.ToString("#######.###")
A decimal is not a string, it does not display the trailing zeros. If you want a string that displays your 3 decimal places including trailing zeros, you can use string.Format:
decimal nn= 23.5;
var formattedNumber = string.Format("{0,000}", nn);

Display double value without scientific notation

I have a null able double value which get values from data base.It retrieve value from data base as '1E-08'. I want to display the value with out scientific notification (0.00000001)
I used the following code.
double? valueFromDB=1E-08;
string doubleValue=valueFromDB.Value.Value.ToString();
string formatedString=String.Format("{0:N30}", doubleValue);
But the value of formatedString is still 1E-08.
You're calling string.Format with a string. That's not going to apply numeric formatting. Try removing the second line:
double? valueFromDB = 1E-08;
string formattedString = String.Format("{0:N30}", valueFromDB.Value);
Or alternatively, specify the format string in a call to ToString on the value:
double? valueFromDB = 1E-08;
string formattedString = valueFromDB.Value.ToString("N30");
That produces 0.000000010000000000000000000000 for me.

double to certain string format

I have this simplified method:
private string GetStringValue(object Value)
{
return ((double)Value).ToString();
}
which spews out:
1.8E-09
I intend to get this format though:
1.8e-009
Is this easily achievable?
Looking at the documentation for custom numeric format strings, I think you want:
// Separate variable just for clarity
double number = (double) Value;
return number.ToString("0.###e+000");
(Use 0.###E-000 if you only want the symbol for negative exponents.)
You need to use String.Format and use the right format string.
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
This should help with decimal format strings.
So
(double)Value.ToString("E")
would do it for en-US.
return string.Format("{0:0.###E+000}", value);

Convert.ToInt32() conditional formatting according to string with comma

string str = e.Row.Cells[index].Text;
int value = Int32.Parse(str, NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo);
if (value >= 100)
e.Row.Cells[index].BackColor = System.Drawing.Color.Green;
Cell values are 168,88 - 125,45 - 75,3
After parsing str returns 16888 - 12545 - 753 , so all of the cells are set as green
how can i compare real values.?
You are using NumberFormatInfo.InvariantInfo. This treats , as thousands separator.
Are you sure this is the correct one? Did you mean to use something like CultureInfo.GetCulture("fr-FR"), where the , is the decimal separator?
Additionally, if you need to preserve the decimal part, why parse to an integer?
This should work better for you:
decimal.Parse(str, NumberStyles.AllowThousands, CultureInfo.GetCulture("fr-FR"));
I think what you're looking for is:
int value = Int32.Parse(str, NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
The NumberFormatInfo tells the Parse function HOW the input should be interpreted. The InvariantInfo reads as Gets the default read-only NumberFormatInfo that is culture-independent (invariant) from msdn.

Convert string to decimal with format

I need convert a String to a decimal in C#, but this string have different formats.
For example:
"50085"
"500,85"
"500.85"
This should be convert for 500,85 in decimal. Is there is a simplified form to do this convertion using format?
Some cultures use a comma to indicate the floating point. You can test this with the following code on an aspx page:
var x = decimal.Parse("500,85");
Response.Write(x + (decimal)0.15);
This gives the answer 501 when the thread culture has been set to a culture that uses the comma as floating point. You can force this like so:
var x = decimal.Parse("500,85", new NumberFormatInfo() { NumberDecimalSeparator = "," });
While decimal.Parse() is the method you are looking for, you will have to provide a bit more information to it. It will not automatically pick between the 3 formats you give, you will have to tell it which format you are expecting (in the form of an IFormatProvider). Note that even with an IFormatProvider, I don't think "50085" will be properly pulled in.
The only consistent thing I see is that it appears from your examples that you always expect two decimal places of precision. If that is the case, you could strip out all periods and commas and then divide by 100.
Maybe something like:
public decimal? CustomParse(string incomingValue)
{
decimal val;
if (!decimal.TryParse(incomingValue.Replace(",", "").Replace(".", ""), NumberStyles.Number, CultureInfo.InvariantCulture, out val))
return null;
return val / 100;
}
This will work, depending on your culture settings:
string s = "500.85";
decimal d = decimal.Parse(s);
If your culture does not by default allow , instead of . as a decimal point, you will probably need to:
s = s.Replace(',','.');
But will need to check for multiple .'s... this seems to boil down to more of an issue of input sanitization. If you are able to validate and sanitize the input to all conform to a set of rules, the conversion to decimal will be a lot easier.
Try this code below:
string numValue = "500,85";
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("fr-FR");
decimal decValue;
bool decValid = decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat, out decValue);
if (decValid)
{
lblDecNum.Text = Convert.ToString(decValue, culInfo.NumberFormat);
}
Since I am giving a value of 500,85 I will assume that the culture is French and hence the decimal separator is ",". Then decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat,out decValue);
will return the value as 500.85 in decValue. Similarly if the user is English US then change the culInfo constructor.
There are numerous ways:
System.Convert.ToDecimal("232.23")
Double.Parse("232.23")
double test;
Double.TryParse("232.23", out test)
Make sure you try and catch...
This is a new feature called Digit Grouping Symbol.
Steps:
Open Region and Language in control panel
Click on Additional setting
On Numbers tab
Set Digit Grouping Symbol as custom setting.
Change comma; replace with (any character as A to Z or {/,}).
Digit Grouping Symbol=e;
Example:
string checkFormate = "123e123";
decimal outPut = 0.0M;
decimal.TryParse(checkFormate, out outPut);
Ans: outPut=123123;
Try This
public decimal AutoParse(string value)
{
if (Convert.ToDecimal("3.3") == ((decimal)3.3))
{
return Convert.ToDecimal(value.Replace(",", "."));
}
else
{
return Convert.ToDecimal(value.Replace(".", ","));
}
}

Categories

Resources