c# Convert.ToDouble format exception error - c#

I'm trying to convert this string to double
Convert.ToDouble("1.12");
and this is the output
System.FormatException was unhandled.
Should I do something like this?
public static double ConvertToDouble(string ParseVersion)
{
double NewestVersion;
try
{
NewestVersion = Convert.ToDouble(ParseVersion);
}
catch
{
ParseVersion = ParseVersion.Replace('.', ',');
NewestVersion = Convert.ToDouble(ParseVersion);
}
return NewestVersion;
}
ConvertToDouble("1.12");
Or is there an easier solution?

double.Parse will use the current culture by default. It sounds like you want the invariant culture:
double d = double.Parse("1.12", CultureInfo.InvariantCulture);
EDIT: Just to be clear, obviously you shouldn't use this if you're trying to parse text entered by a user in a different culture. This is for use when you've received data in the invariant culture (as most machine-to-machine data text-based formats are) and want to enforce that when parsing.

You don't have to replace . to ,.. however a better way is to use the .net TryParse method like:
double d;
if (double.TryParse("your string data", out d)
{
Console.WriteLine(d);
}
Edit: Also note that by replacing . by , you are getting a wrong results, for instance 1.12:
double d = double.Parse(1.12);//d will equals to 1.12
double d = double.Parse(1,12);//d will equals to 112.0

Convert.ToDouble uses Double.Parse internally. If you are unsure of the culture context, you should use an overload of Double.Parse precising the culture:
double d = double.Parse("1.12", CultureInfo.InvariantCulture);

Keep in mind, this problem can depend on where the input string comes from. If it is read from a database as an object, you might solve your problem by keeping it as an object and using Convert.ToDouble() as follows:
public double Double_fromObject(object obj)
{
double dNum = 0.0;
if (obj.ToString() != string.Empty) // the Convert fails when ""
{
try
{
dNum = Convert.ToDouble(obj);
}
catch (SystemException sex)
{
// this class's error string
LastError = sex.Message;
}
}
return (dNum);
}

Related

How to convert reader.Read string to currency format in c#?

I built the below code, trying to convert reader[BalanceAmt] to a currency, i.e. $23,456.78. I can't seem to get it to work. It's still returning "23456.782" Any ideas?
while (reader.Read())
{
string MyNum = reader["BalanceAmt"].ToString();
String.Format("{0:#,###0}", MyNum);
BalanceBox.Text = (MyNum);
}
If reader["BalanceAmt"] returns a string then to get your numeric formatting to work, you need to convert it into a number before converting it to currency - i.e.
var myNum = Convert.ToDecimal(reader["BalanceAmt"]);
BalanceBox.Text = myNum.ToString("C");
Note the "C" currency format specifier argument passed into the decimal.ToString method - see MSDN Decimal.ToString Method Documentation.
The Convert.ToDecimal method will throw an exception if reader["BalanceAmt"] contains anything that Convert.ToDecimal is unable to cope with (non-numeric characters).
You might want to put a try..catch around this, or if you don't want an exception to be thrown, use Decimal.TryParse inside an if check:
var balanceAmt = reader["BalanceAmt"];
if (decimal.TryParse(balanceAmt, out var myNum))
{
BalanceBox.Text = myNum.ToString("C");
}
while (reader.Read())
{
BalanceBox.Text = reader["BalanceAmt"].ToString("c");
}
In your code String.Format("{0:#,###0}", MyNum); MyNum never changes...only formatted.
Please use this:
BalanceBox.Text = String.Format("{0:#,###0}", Convert.ToDouble(MyNum));

Formatting Exception when parsing textbox into double

A = double.Parse(ABox.Text);
B = double.Parse(BBox.Text);
C = double.Parse(CBox.Text);
a = double.Parse(a_Box.Text);
b = double.Parse(b_Box.Text);
c = double.Parse(c_Box.Text);
Every time this code is run in my system, it throws an Formatting exception. The textBoxes are empty when the error appears, do they have to have at least a zero in them?
Yes
(An empty string can't be parsed into a double)
Instead of Parse you can consider using TryParse:
double number;
if (Double.TryParse(ABox.Text, out number))
{
...
}
else
{
...
}
Yes. Parse will throw an exception if the input is an empty string. You'll either need to check first whether the textbox is empty before parsing it or you can use TryParse.

Find Currency Symbol in Currency Data C#

I want to find which Currency Symbol exists in Currency Format data.
For example, Input String = $56.23
public class FormatConverter
{
private CultureInfo _cultureInfo;
public void UpdateCultureInfo()
{
Thread.CurrentThread.CurrentCulture.ClearCachedData();
var thread = new Thread(
s => _cultureInfo = Thread.CurrentThread.CurrentCulture);
thread.Start();
thread.Join();
}
Bool TryParseCurrencySymbolAndValue(string input, out string CurrencySymbol,
out double value)
{
if(_cultureInfo == null)
UpdateCultureInfo();
try{
// Convert Currency data into double
value = Double.Parse(input, NumberStyles.Number | NumberStyles.AllowCurrencySymbol);
// How to extract Currency Symbol?
CurrencySymbol = "$";
return true;
}
catch(Exception ex){ /* Exception Handling */}
return false;
}
}
I want to extract "$" symbol from a string and 56.23 separately and then I want to apply CultureInfo to 56.23 into French Format. The output should be $56,23.
In some cases, input might be "Euro sign" or some other currency symbol in the beginning or in the end of input string.
I know how to convert into CurrentCulture for Numeric part. I don't know how to extract currency Symbol from a string.
It sounds like you already know how to parse the string into a number type (correct me if I'm wrong). You're using double in your example, I would suggest decimal but that's your choice.
To get the currency symbol you can use a simple regular expression
Regex ex = new Regex(#"\p{Sc}");
CurrencySymbol = ex.Match(input).Value;
I hope that helps.
Look at this link as well to give you and idea as to the many different ways you can find and or use IndexOf
[IndexOf String Examples][1]
the question is will the format always have the $ as the first char..? if the answer is yes
regardless of USC or Foreign Currency use the String.IndexOf Method
String.IndexOf("$")
here is a coded example that you may look at
using System;
class Program
{
static void Main()
{
// A.
// The input string.
const string s = "Tom Cruise is an Idiot he should pay $54.95.";
// B.
// Test with IndexOf.
if (s.IndexOf("$") != -1)
{
Console.Write("string contains '$'");
}
Console.ReadLine();
}
}
Output
string contains '$'
Can you please try with?
float curSymbol;
bool isValid = float.TryParse(curValue,
NumberStyles.Currency,
CultureInfo.GetCultureInfo("en-US"), out curSymbol);
Get the curSymbol. :) Be sure to pass currency values with symbol:)

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

C# > Convert string to double when input=""

I would like to convert a string to double (very basic question isn't it ?)
string input = "45.00000";
double numberd = Double.Parse(input, CultureInfo.InvariantCulture);
=> my code works and I am very happy.
However I may have the following
string input = "";
double numberd = Double.Parse(input, CultureInfo.InvariantCulture);
In this case my code does not work and I get a Exception error ;(
I wonder how I can manage such situation. Ideally when I get this I would like to have my variable numberd equal to null.
Can anyone help me ?
Thx
Microsoft recommends using the Tester-Doer pattern as follows:
string input = "";
double numberd;
if( Double.TryParse(input, out numberd) )
{
// number parsed!
}
Use a Double for parsing, but a Double? for storing the value, perhaps?
Double number;
string input = ""; // just for demo purpose, naturally ;o)
Double? nullableNumber =
Double.TryParse(input, NumberStyles.Any, CultureInfo.InvariantCulture, out number)
? (Double?)number
: null;
// use nullableNumber
Primitive types like double cannot be null. You can have a nullable version with double? but, Double.Parse does not return a double? (just a plain double).
You could use Double.TryParse and check the return condition and set a double? to null accordingly if that would suit better.
Why not just catch the exception and set your variable?
double numberd;
try {
numberd = Double.Parse(input, CultureInfo.InvariantCulture);
} catch (System.FormatException e)
numberd = 0.0;
}
Alternatively, you can use Double.TryParse
Add an if statement comparing strings or surround with try/catch block.
Assuming you aren't worried about other invalid values besides empty strings, here's a simple one-liner:
Double? numberd = (input.Length == 0) ? null : (Double?)Double.Parse(input, CultureInfo.InvariantCulture);
mzabsky was on the right path, however his solution won't build and you shouldn't hard-code empty string - it's better to check the length of a string.
How about
Double? numberd = String.IsNullOrEmpty(str) ? null : Double.Parse(str)
In my application, I am parsing CSV files and I want these empty strings to be zero so I return 0.0 instead of null and it's all good.
5 more

Categories

Resources