Convert string to Double C# - c#

I have a field in DB which is float. My application is WindowsForm. I need to convert the value in textbox of the format 43.27 to double.
When I do this COnvert.ToDouble(txtbox.Text) I get exception saying input string is wrong format.
How to rectify this issue

Try specifying a culture when parsing:
// CultureInfo.InvariantCulture would use "." as decimal separator
// which might not be the case of the current culture
// you are using in your application. So this will parse
// values using "." as separator.
double d = double.Parse(txtbox.Text, CultureInfo.InvariantCulture);
And to handle the error case for gracefully instead of throwing exceptions around you could use the TryParse method:
double d;
if (double.TryParse(txtbox.Text, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d))
{
// TODO: use the parsed value
}
else
{
// TODO: tell the user to enter a correct number
}

When you want to convert a string to number, you need to be sure which format does the string use. E.g. in English, there is a decimal point (“43.27”), while in Czech, there is a decimal comma (“43,27”).
By default, the current locale is used; if you know the number uses the English conversion, you need to specify the culture explicitly, e.g.
Convert.ToDouble(txtBox.Text, CultureInfo.InvariantCulture);

Related

System.FormatException if use new CultureInfo("id-ID") - Indonesian culture

I am trying to convert exponential value to decimal with Indonesian culture but it does not work..
string _ex = "1.2162876E-5";
decimal _dec = decimal.Parse(_ex, NumberStyles.Float, new CultureInfo("id-ID"));
it thrown me System.FormatException
but it works properly if I use en-US
decimal d0 = decimal.Parse(_ex, NumberStyles.Float, new CultureInfo("en-US"));
what I missed?
please help
thanks a lot
Don2
In id-ID, the decimal separator (CultureInfo.NumberFormat.NumberDecimalSeparator) is ",", so it is expecting "1,2162876E-5" as the input (meaning the numeric value zero point zero zero zero zero one two etc). If the input is using a "." to mean decimal point, then you should probably use the invariant culture to parse it (CultureInfo.InvariantCulture), instead of a locale-specific culture.

Converting string with many leading zeros to decimal

How can I convert string which looks like this:
0005.47
to decimal value 5.47.
This value is kept in newStringArray[1] so I did this: Convert.ToDecimal(newStringArray[1])
But as a result I got this value : 547
What's the point here?
Your culture settings think that a point is not the decimal separator but the thousands separator.
You need to pass the information about the culture you want to use to Convert.ToDecimal. It can be done passing the CultureInfo.InvariantCulture property to inform the converter to use the proper decimal symbol when converting.
string test = "0005.47";
decimal value = Convert.ToDecimal(test, CultureInfo.InvariantCulture);

How do I convert string to decimal?

I have this textbox that accepts numbers, commas, and periods.
Let's say this textbox contains input 14,500.00
I tried to convert this number to decimal with Convert.ToDecimal(textbox.text) but it's not working. Convert.ToDecimal() to textboxes that contain input that has the format XXXX.DD are converted to decimal but input with format X,XXX.DD or any input with a thousand separator results to error:
Input string was not in correct format
Is Convert.ToDecimal() appropriate in this case?
ADDITIONAL INFO:
Here is the form. If I click 'Add', the product of 'Price' and 'Quantity' should be displayed as 'Amount' in the datagridview.
The syntax in the 'Add' button includes:
DataRow dr;
dr = dsDetail.Tables["SalesOrderDetails"].NewRow();
dr["Amount"] = Convert.ToDecimal(txtSellingPrice.Text) * Convert.ToDecimal(txtQuantity.Text);
The Amount field in my SalesOrderDetails table has the datatype decimal(18,2)
You can force a culture and use decimal.Parse
decimal d = decimal.Parse("14,500.00", CultureInfo.InvariantCulture); // 14500
Is Convert.ToDecimal() appropriate in this case?
Yes, you could also continue to use Convert.ToDecimal if you want:
d = Convert.ToDecimal("14,500.00", CultureInfo.InvariantCulture);
I would give decimal.TryParse a go
decimal d;
if(decimal.TryParse(textbox.Text, out d))
{
//do something
}
I suspect you're using a culture that defines . as the thousands separator and , as the decimal separator. If you want to force , and . as the thousands and decimal separators, respectively then use:
decimal value = Convert.ToDecimal(textbox.text,CultureInfo.InvariantCulture);
Is Convert.ToDecimal() appropriate in this case?
It's fine - the main difference is it supports more types than decimal.Parse, which only supports strings.
I agree with #matt_lethargic, but offer a more complete solution. Tested with XUnit :)
[Theory]
[InlineData("en-US","44.00")]
[InlineData("es-PE", "44,00")]
[InlineData("es-PE", "44.00")]
[InlineData("es-PE", "0.01E-15")]
[InlineData("es-PE", "0,01E-15")]
public void ParsesDeciaml(string culture, string dec)
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);
decimal d;
if (!decimal.TryParse(dec, out d)
&& !decimal.TryParse(
dec,
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.CurrentCulture,
out d
)
&& !decimal.TryParse(
dec,
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture,
out d
)
) Assert.False(true, dec);
}
That way you can capture values with exponential formats.

Convert String to Double with Known Format

I need to convert a string back to a double, but the string is not always the same format. In one case it is "N0", in another "#,##", and yet another is currency "C0". The good thing is, I know what format the string is in as earlier in the process it was converted from double to string.
How can I convert back to a double. The numeric only values double.parse or Convert.ToDouble with ease, but the currency values do not.
string format = "{0:C0}";
double dollar = 1,234.00;
string dollarString = String.Format(format, doubleValue); // == "$1,234"
double newDollar = Convert.ToDouble(dollarString); // Fails
This last line is where the issue is. I'm assuming I need to use IFormatProvider or Culture or something, but I'm not exactly sure.
I cannot specifically reference the format is a Currency as the "format" isn't always a currency.
Ideas?
As I was typing this I came up with the following. Further feedback on whether this is a good way of doing it or if I might run into issues later.
double newDollar;
double.TryParse(dollarString, NumberStyles.Any, CultureInfo.CurrentCulture.NumberFormat, out newDollar);
If you're using CultureInfo.CurrentCulture make sure to you set the CurrentCulture of your thread.
Else it can end up in parsing it the wrong way (depending on the language settings on your computer).
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Then you can safely use this:
double.TryParse(dollarString, NumberStyles.Any,
CultureInfo.CurrentCulture.NumberFormat, out newDollar);
Alternatively, you can create a function like this (To get the right format without setting the culture).
side note: In Switzerland, this could cause troubles because the euros can still be parsed.
So 5,05 (€) would successfully be parsed to 505 (CHF). Trust me, you don't want this to happen.
public static double GetDouble(string value, double defaultValue)
{
double numberToConvert;
if (!double.TryParse(value, System.Globalization.NumberStyles.Any,
CultureInfo.CurrentCulture, out numberToConvert) &&
!double.TryParse(value, System.Globalization.NumberStyles.Any,
CultureInfo.GetCultureInfo("en-US"), out numberToConvert) &&
!double.TryParse(value, System.Globalization.NumberStyles.Any,
CultureInfo.InvariantCulture, out numberToConvert))
{
numberToConvert= defaultValue;
}
return numberToConvert;
}

Convert dd/MM/yyyy to yyyy/MM/dd?

I want to convert a string '30/12/2012' to '2012/12/30'. My application is set to "en-CA" however the database accepts yyyy/MM/dd as default.
How can I do this without depending on the current culture info set
at server?
As all the comments have said, but none of the answers have said so far: don't pass this to the database as a string.
Parse any text you receive as early as possible, then use DateTime to represent it everywhere else, including how you send it to the database, via parameterized SQL1. This goes for values of all kinds: convert it into the "natural" type for the data as soon as possible, and keep it in that natural representation for as long as possible. A date isn't a string, and you should only convert it to a string if you really, really need to - ideally just before displaying it to a user.
The parsing can be done with DateTime.ParseExact or DateTime.TryParseExact depending on whether this is "suspicious" data (e.g. from a user) or data which should really be correct and for which an exception is the most appropriate reaction to unparseable values. I suggest you pass in CultureInfo.InvariantCulture with your custom format string. For example:
DateTime date = DateTime.ParseExact(text, "dd/MM/yyyy",
CultureInfo.InvariantCulture);
(If you do a lot of date/time work, you may also want to consider using my Noda Time project which allows you to express the value in a richer way - in this case you'd probably use LocalDate.)
1 If you're not already using parameterized SQL, but are instead baking values directly into the SQL, you have bigger problems than date/time conversions.
You can specify CultureInfo in Format and most ToString functions.
I.e. DateTime.ToString(CultureInfo) and DateTime.Parse(string, CultureInfo) will let you pars string in one culture (i.e. current or new CultureInfo("en-CA")) and format with another like new CultureInfo("en-us").
Note: you may consider running all DB access under some other culture (i.e. en-US) by setting Thread.CurrentCulture as sometimes number fomats are also impacted (if numbers are storead as string).
If its going to always be in the same format. Then split it on the / character
string[] tempsplit = datestring.Split('/');
and then put it back together
string joinstring = "/";
string newdate = tempsplit[2] + joinstring + tempsplit[1] + joinstring + tempsplit[0];
simple.
First convert your string to DateTime format using
DateTime dt = Convert.ToDateTime("your string value");
Then save it in string using:
string st=dt.ToString("yyyy/MM/dd");
This will convert your date format to any desired format you want without depending on culture
Without going into the issue what format the database accepts or not, you can do the conversion like this:
Convert the String to Datetime like explained here
Change the format and convert it to string again like this
This seems to work.
var x = new string[] { "2012/06/12", "20/06/2012", "111/111/1111" };
foreach (var ds in x)
{
DateTime d = default(DateTime);
try
{
d = DateTime.Parse(ds, CultureInfo.GetCultureInfo("en-CA"));
}
catch (Exception ex)
{
try
{
d = DateTime.ParseExact(ds, "yyyy/MM/dd", CultureInfo.InvariantCulture);
}
catch
{
}
}
if (d == default(DateTime))
Console.WriteLine("error");
else
Console.WriteLine(d.ToString());
}

Categories

Resources