Formatting a String to be Converted to Double
I'm trying to convert a string
to double
. The incoming string is always going to be a whole number...no decimals. So, for example "90".
double percentToCheck = Convert.ToDouble(String.Format("{0:0.00}", SomeEntity.KeyIDs.SomePercentTrigger));
SomePercentTrigger
is the % that I will be converting.
I get a "string is not in the correct format" error so how 开发者_开发百科should I format this string? I've got to format it because if I don't I get the same error with just this during the conversion:
double percentToCheck = Convert.ToDouble(SomeEntity.KeyIDs.SomePercentTrigger);
UPDATED:
SomePercentTrigger
is simply a string
such as "80"..it'll always be a whole number too.
Update:
Your string is "52.0"
.
It must be the '.'
that causes the FormatException
.
You are probably on a machine where '.'
is not set as the decimal point (e.g. I live in Germany and use German regional settings. Our decimal point is ','
)
To get around this problem you need to parse the string using CultureInfo.InvariantCulture
.
var value = double.Parse(myString, CultureInfo.InvariantCulture);
InvariantCulture
should be used for the parts of your application that revolve around data storage. Make sure you use it as well when converting doubles to strings Console.WriteLine(value.ToString(CultureInfo.InvariantCulture));
I suspect that SomeEntity.KeyIDs.SomePercentTrigger
has some invalid characters in it (something other than digits, '.' and a optional leading '-'), say for example "80%"
So you're getting a FormatException
on this line
double percentToCheck = Convert.ToDouble(String.Format("{0:0.00}", SomeEntity.KeyIDs.SomePercentTrigger));
because {0:0.00}
formatting rules are only valid for numeric values.
Also you get the very same exception here:
double percentToCheck = Convert.ToDouble(SomeEntity.KeyIDs.SomePercentTrigger);
because "80%" can not be converted into a double.
You should either
- put some logging right in front of the failing statement
- or debug that code
and see what the actual content of SomeEntity.KeyIDs.SomePercentTrigger
is.
Use double.Parse(string)
or alternatively double.TryParse(string, out value)
It doesn't make sense to try to format a string. You would have to parse it to a number first in order to format it. Anyhow, there is no problem in parsing a number without decimals as a double, so the string is probably not containing what you think it does.
If the string contains a number in integer format, parse the string as an integer, and then convert the integer to a double:
double percentToCheck = (double)Int32.Parse(SomeEntity.KeyIDs.SomePercentTrigger);
精彩评论