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);
Related
I'm trying to get a string formatted float number (e.g. "3.14") from a COM port.
I used Convert.ToSingle() but it threw exception "Input string was not in a correct format" And while debugging, I found that double, float and decimal numbers are separated by '/' instead of '.'; for example 3.14 was 3/14.
My system language is English, but date and time formats are in Persian (Windows 10). In Persian, we use / instead of . as the decimal symbol.(۳/۱۴ = 3.14)
Is there any way to make program independent of system regional settings and force it to always use '.' as decimal symbol?
Using Convert.ToSingle will attempt to convert an object to a floating-point number based on the system's region settings, as you have already noticed.
In order to reliably convert a string that is, for example, in US-English format, you can provide an additional argument of the type IFormatProvider to the method.
string text = "3.5";
IFormatProvider culture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
float number = Convert.ToSingle(text, culture);
The result stored in number be 3.5, i.e. the number halfway between three and four, independent of your system settings. For example, the above code works as expected on my computer, even though it's set to the German (de-DE) region, which represents the same number as 3,5.
See also the documentation of Convert.ToSingle for details.
I have this code:
string x = "-0.228469369833477";
Single s = Convert.ToSingle(x);
Console.WriteLine(s);
The console outputs: -2,284694E+14 .
What can I do to make it output: -0.228469369833477?
To output the number in its original form:
var s = -0.228469369833477;
Console.WriteLine(s.ToString("0.#######################"));
Note that s is likely a double, not a single. By using single you're very likely losing digits. To get enough precision to represent all of the digits, use Convert.ToDouble() instead.
To ensure that the number gets parsed properly in your locale, use CultureInfo.InvariantCulture, as other answers have stated.
A decimal will give you 28-29 significant digits of precision, with better precision and without the scientific notation problems.
Further Reading
Custom Numeric Format Strings
Single s = Single.Parse(x, CultureInfo.InvariantCulture);
If you want it to output that exact number, you can't use a float because it doesn't give you the precision you want. Try using a double.
double s = Double.Parse(x, CultureInfo.InvariantCulture);
Well, '.' is treated as a thousand separator (and ',' as decimal one) in your current culture (e.g. Russian Culture - "RU-ru" works like that) and since thousand separator ignored on conversion you have -228469369833477 (or -2,284694E+14).
string x = "-0.228469369833477";
// To ensure that '.' is treated as decimal separator
// lets put culture explicitly - CultureInfo.InvariantCulture
Single s = Convert.ToSingle(x, CultureInfo.InvariantCulture);
Console.WriteLine(s);
However, you have too many digits to represent for a Single and all you can return is -0.2284694 (not -0.228469369833477). If you want exact correspondence you have to use Double instead of Single:
Double s = Convert.ToDouble(x, CultureInfo.InvariantCulture);
// -0.228469369833477
Console.WriteLine(s, CultureInfo.InvariantCulture);
You can use
Console.WriteLine(string.Format("{0:N8}", s));
to output the single to 8 decimal places.
You can also specify the culture while doing the string formatting:
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0:N8}", s));
Here's a working fiddle: https://dotnetfiddle.net/nS9qXh
I'm having trouble with a very simple problem. Basically I'm taking a string, like "$30.00", and removing the '$' and then trying to convert it to a decimal. Although I keep getting an error stating that the string isn't in the correct format. Not sure what to do from here...
string freightstart = PostFregihtAmount.ToString();
freightstart = freightstart.TrimStart('$');
decimal freight = Decimal.Parse(freightstart);
I tried the following, per Alex Skiba's suggestion in the comments:
Decimal.Parse(freightstart, System.Globalization.CultureInfo.InvariantCulture);
This is the error I receive upon debugging:
This is a plugin for our onsite CRM 2011 system and some fields that I have to reference on the quote form are currency fields. When I query the data they come back as string formats, hence the example "$30.00". Long story short I need to convert it to decimal so that I may do my tax solution.
Try explicitly allowing the decimal point when you parse the string, as well as the currency symbol (then you don't have to trim the $ before parsing):
var freight = Decimal.Parse("$30.00",
NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint);
Is there a fast way to convert numbers with exponential notation (examples: "0.5e10" or "-5e20") to decimal or double?
Update: I found Parse a Number from Exponential Notation but the examples won't work for me unless I specified a culture.
Solution:
double test = double.Parse("1.50E-15", CultureInfo.InvariantCulture);
If your culture uses . as the decimal separator, just double.Parse("1.50E-15") should work.
If your culture uses something else (e.g. ,) or you want to make sure your application works the same on every computer, you should use InvariantCulture:
double.Parse("1.50E-15", CultureInfo.InvariantCulture)
The standard double.Parse or decimal.Parse methods do the job here.
Examples:
// AllowExponent is implicit
var number1 = double.Parse("0.5e10");
Debug.Assert(number1 == 5000000000.0);
// AllowExponent must be given explicitly
var number2 = decimal.Parse("0.5e10", NumberStyles.AllowExponent);
Debug.Assert(number2 == 5000000000m);
Also, see the MSDN article Parsing Numeric Strings for more information. As long as the NumberStyles.AllowExponent option is specified to the Parse method (which it is by default for double), parsing such strings will work fine.
NB: As the questioner points out, the exponential notation of "e10" for example does not work in all cultures. Specifying en-US culture however ensures that it works. I suspect CultureInfo.InvariantCulture should also do the trick.
#Noldorin is correct try this code:
string str = "-5e20";
double d = double.Parse(str);
Console.WriteLine(str);
the Math.Round does it well, it will reder the number so that will remove, here is how to use it:
Math.Round(Double.Parse("3,55E-15"),2)
In my app I parse a value from xml (string) to a double.
The value in the xml happens to have the dot as a fraction seperator whereas the system takes the current system settings and can have a different separator (dev system takes the comma for example).
Is there a way to tell double.TryParse() the dot is the fraction separator?
Should I manually replace the dot with the system's fraction separator? If so, how do I get this?
What you should do, in this situation, is use the XmlConvert class and its members to convert the value like it exists in the XML file to a regular variable. :)
Pass CultureInfo.InvariantCulture into double.TryParse:
double value;
bool success = double.TryParse(text, NumberStyles.Float,
CultureInfo.InvariantCulture,
out value);
(For genuinely standard XML formatting, Frederik's suggestion of using XmlConvert is the best idea though.)