double to certain string format - c#

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);

Related

How to prevent inserted currency sign if value is 0?

I want to ask is there a way to prevent dollar sign to be inserted if the value is 0?
I am using string function Format to make currency sign #string.Format("{0:C}",0)) update my output is $0.00
Make an extension method to do this:
public static string ToCurrency(this int value)
{
return value == 0 ? value.ToString("N2") : value.ToString("C");
}
You can use a three-part custom format string with ; separating the different sections. The first section describes the format applied to positive numbers; the second applies to negative numbers; and the third applies to zero:
const string format = "{0:$#,0.00;-$#,0.00;0.00}";
string.Format(format, 1.23d) // => $1.23
string.Format(format, -1.23d) // => -$1.23
string.Format(format, 0d) // => 0.00
Sadly, this only works with custom formats, meaning you cannot use built-in specifiers like C in the individual sections. One consequence of this is that you cannot rely on the system choosing which currency symbol to include based on the thread culture; you must include it directly in the format string.

String.Format is not working properly

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.

Easy way to check FormatString is valid?

Is there an easy way to check if a format string is valid? For example the following is code that we use to test a number format string;
public static bool IsValidFormatStringNumber(string FormatString)
{
try
{
const decimal number = 0.056m;
var formattedNumber = number.ToString(FormatString);
return formattedNumber.Length > 0;
}
catch
{
return false;
}
}
We're trying to catch an exception or determine if the resulting string has no length. This test fails however as a format string of "hsibbur" (Any rubbish) results in a string of "hsaibbur", which has length.
We want to do the same test for Percent and Date format string.
If you just want to check for standard format strings, just check that your format strings are part of that list.
If you want to check for custom format strings (that are not "Other" or "Literal strings"), you can probably craft a regex to do it.
Other than that, since format strings can be arbitrary strings, I don't think validation even applies.
If FormatString is equal to formattedNumber, that could be another case for returning false.

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(".", ","));
}
}

How to Parse a String to Double

Here is my string
20.0e-6
I'm parsing it like
String Ans=Double.Parse("20.0e-6")
Now i'm getting the result like 2E-05
But the required output should be like
0.00002
How to get this?
The result of Double.Parse is a Double, not a string. You need to output a string from the double, using ToString.
You should also use an overload of Double.Parse that has a NumberStyles parameter. Using the Float value allows exponent notation:
string Ans=Double.Parse("20.0e-6", NumberStyles.Float).ToString("0.#####");
If you don't want to risk exceptions (InvlidCastException for example), you can use TryParse:
Double res;
if (Double.TryParse("20.0e-6", NumberStyles.Float,
CultureInfo.InvariantCulture ,res))
{
string Ans = res.ToString("0.#####");
}
It's the same number, but if you want to modify the output of the string, use a formatter on your ToString()
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
So
String Ans=Double.Parse("20.0e-6").ToString("0.0####")
One way to get the result you want is to use String.Format as follow:
double x = 20.0e-6;
string y = string.Format("{0:0.######}",x);
Console.WriteLine(y);
Given your example, this outputs the value 0.00002
EDIT
I've just realised that this is actually the opposite of your question so in the aim of keeping the answer useful i'll add the following:
Given a string, you can parse as double and then apply the same logic as above. Probably not the most elegant solution however it offers another way to get the result you want.
string x = "20.0e-6";
var y = double.Parse(p);
Console.WriteLine(String.Format("{0:0.######}",y));

Categories

Resources