I have a problem with parsing a string to a double. I have a StreamWriter reading lines from a text file. The text file has the following lines:
17-09-2012: (100,98)
17-09-2012: (50,57)
Now, I want to use the values from inside the parantheses, add them together and display them in a textbox. So far I have the following:
int counter = 0;
double res = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("d:\\test.txt");
while ((line = file.ReadLine()) != null)
{
string par = Regex.Match(line, #"\(([^)]*)\)").Value;
double par2 = double.Parse(par);
res += par2;
counter++;
}
file.Close();
textBox1.Text = res.ToString();
However, apparently the input string is not in a correct format, which I find rather odd, since the regex should remove everything but the numbers inside the parantheses. I have even checked for this by writing the string to the textbox without first adding them together, and it showed "100,9850,57". So truly, I do not understand, why it cannot convert the string to a double.
I hope you can tell me, what I am doing wrong.
Your "par" variable is containing a string that looks like: "(100,98)" which is why it's failing to parse.
change your regex to (?<=\()(([^)]*))(?=\))
You can try with - based on InvariantCulture
var culture = CultureInfo.InvariantCulture;
double result = double.Parse(par , culture);
Setting your regex to (?<=\()(([^)]*))(?=\)) and using this helper should solve your problems:
public static double ParseDouble(string input)
{
// unify string (no spaces, only . )
string output = input.Trim().Replace(" ", "").Replace(",", ".");
// split it on points
string[] split = output.Split('.');
if (split.Count() > 1)
{
// take all parts except last
output = String.Join("", split.Take(split.Count() - 1).ToArray());
// combine token parts with last part
output = String.Format("{0}.{1}", output, split.Last());
}
// parse double invariant
double d = Double.Parse(output, CultureInfo.InvariantCulture);
return d;
}
You can force double.Parse to use a culture that uses , as a decimal separator, like this:
CultureInfo culture = new CultureInfo("de-DE");
double d = double.Parse(par, culture);
That's a good idea anyway, if you want your program to work also on computers with different regional settings.
I made it work, by making a try, catch:
string par = Regex.Match(line, #"(?<=\()(([^)]*))(?=\))").Value;
try
{
double par2 = double.Parse(par);
res += par2;
}
catch
{
}
Thanks, everyone for your help.
Related
How to get correct double digit from string.
string first = "23.3";
string second = "23,3";
For now I used the sample parser for parse the number in double format:
double number = double.Parse(first);
double another = double.Parse(second);
So if I used en-US culture and for decimal separator used '.' then the result will be number = 23.3 and another = 233.
So my question is do is possible to ignore the decimal separator and when is parse in both case to return result = 23.3.
In addition to replace comma with dot, you need to supply a proper number format:
public double ParseMyString(string myString)
{
return double.Parse(myString.Replace(',', '.'),
new NumberFormatInfo() {NumberDecimalSeparator = "."});
}
Another option to replace the separator on a broader scope is to use this:
Thread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
You will still need to replace comma with dot though.
You can play a trick:
private string ReplaceSeparator(string Num)
{
return Num.Replace(",", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator).Replace(".", CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
}
.....
string first = "23.3";
string second = "23,3";
first = ReplaceSeparator(first);
second = ReplaceSeparator(second);
double number = double.Parse(first);
double another = double.Parse(second);
I am trying to convert a System.string to a System.double, the input is: He: 4.002602 amu
Code:
string[] data = line.Replace(" ", "").Replace("amu", "").Split(new char[] { ':' });
double i = Convert.ToDouble(data[1]);
I have tried:
string[] data = line.Replace(" ", "").Replace("amu", "").Split(new char[] { ':' });
double i = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
You can use following regular expression without splitting a string which mixed with number and words:
// using System.Text.RegularExpressions
var resultString = Regex.Match(line, #"\d.\d+").Value;
If format of input is something+blank+doubleNumber+blank+something you can use following code:
string line = "He: 4.002602 amu";
int intLspacePos = line.IndexOf(" ") + 1;
int intRspacePos = line.LastIndexOf(" ");
string strNumber = line.Substring(intLspacePos, intRspacePos - intLspacePos);
double dblNumber = Convert.ToDouble(strNumber);
Instead of Convert.ToDouble() use the double.Parse() method, preferably using the invariant culture when the user input is always using a period sign as decimal separator.
So try something like this:
double i = double.Parse(data[1], CultureInfo.InvariantCulture);
EDIT:
I've seen in the screenshot you posted in the comments above that you're not actually checking the contents of data[1] before passing it to the Convert.ToDouble method.
According to MSDN the only case when a FormatException is thrown should be when providing a non-numeric text value (see here). Therefor I'd suggest to add a check for empty strings and null values before, passing the value to the Convert.ToDouble() method. Try updating your code to something like this:
foreach (string line in raw) {
string[] data = line.Replace(" ", "").Replace("amu", "").Split(new char[] { ':' });
if (!string.IsNullOrWhiteSpace(data[1]) {
double i = Convert.ToDouble(data[1], CultureInfo.InvariantCulture);
} else {
// Invalid value in data[1]
// Maybe set a breakpoint here and investigate further if necessary
}
}
If this still throws a FormatException then the contents of data[1] must be some non-numeric and non-empty text value, so in that case you should probably check the contents of the data array using the debugger and find out how / why that invalid value got there.
you can convert with specific culture info as below. 2057 is LCID for English (UK).
double i = Convert.ToDouble(data[1], CultureInfo.GetCultureInfo(2057));
I need to extract a variable length decimal number from a string using c# and .NET. The input string is like $PTNTHPR,352.5,N,2.3,N,4.6,N,16*. I need the first occurrence of decimal number, i.e the 352.5 part. The numerical value ranges from 0.0 to 360.0 and I need that number from that string.
I searched a lot and got solution for a fixed length sub string but here I have variable length to extract. I have not tried with any code yet.
If it is always in this format you can use String.Split and decimal.Parse
var data = #"$PTNTHPR,352.5,N,2.3,N,4.6,N,16*";
var d = decimal.Parse(data.Split(new[]{','})[1]);
Console.WriteLine(d);
This is just a sample code to guide you. You should add additional exception handling logic to this, Also consider using decimal.TryParse
If you want to find the first occurance of decimal value you split the string and parse them one by one.
var data = #"$PTNTHPR,352.5,N,2.3,N,4.6,N,16*";
var splited = data.Split(new[]{','});
decimal? value = null;
foreach (var part in splited)
{
decimal parsed;
if (decimal.TryParse(part, out parsed))
{
value = parsed;
break;
}
}
Console.WriteLine(value);
First occurence in any of the tokens? Use String.Split to separate them and LINQ to find the first. You can use decimal.TryParse to check if it's parsable:
decimal? firstParsableToken = "$PTNTHPR,352.5,N,2.3,N,4.6,N,16*".Split(',')
.Select(s => s.TryGetDecimal(NumberFormatInfo.InvariantInfo))
.FirstOrDefault(d => d.HasValue);
Used this simple extension method to parse it to decimal?:
public static decimal? TryGetDecimal(this string item, IFormatProvider formatProvider = null, NumberStyles nStyles = NumberStyles.Any)
{
if (formatProvider == null) formatProvider = NumberFormatInfo.CurrentInfo;
decimal d = 0m;
bool success = decimal.TryParse(item, nStyles, formatProvider, out d);
if (success)
return d;
else
return null;
}
If the string is always comma separated, can you not use string.Split() to get each section, then use double.TryParse() to test if that part is numeric?
public static class Helper
{
public static string MyExtract(this string s)
{
return s.Split(',').First(str => Regex.IsMatch(str, #"[0-9.,]"));
}
}
Use it like this: string str = "$PTNTHPR,352.5,N,2.3,N,4.6,N,16*".MyExtract();
Then convert it to double/decimal if you need it.
I get from a webservice the following strings:
12.95
or
1,200.99
Is there an option to convert these values to the following values without manipulating the string?
12,95
or
1200,99
I tried it with some Culture options but didn't get it right...
EDIT
I tried this:
//return string.Format( "{0:f2}", Convert.ToDecimal( price ) );
//return string.Format(CultureInfo.GetCultureInfo("de-de"), "{0:0}", price);
NumberFormatInfo format = new System.Globalization.NumberFormatInfo();
format.CurrencyDecimalDigits = 2;
format.CurrencyDecimalSeparator = ",";
format.CurrencyGroupSeparator = "";
return decimal.Parse(price).ToString(format);
var input = "1,200.99";
//Convert to decimal using US culture (or other culture using . as decimal separator)
decimal value = decimal.Parse(input, CultureInfo.GetCultureInfo("en-US"));
//Convert to string using DE culture (or other culture using , as decimal separator)
string output = value.ToString(CultureInfo.GetCultureInfo("de-DE"));
Console.WriteLine(output); //1200,99
What about something like this:
double number;
double.TryParse("1,200.99", NumberStyles.Any, CultureInfo.CreateSpecificCulture("en-US"), out number);
var formattedNumber = number.ToString(CultureInfo.CreateSpecificCulture("de-DE"));
Then return or write out formattedNumber (whatever you need to do).
Yes and no. First, what you have is a string, and so you cannot change the formatting of it as you're attempting to. However, to achieve what you would like, you can parse the string into a decimal value and then use the formatting options for decimals to display it in any reasonable way.
You may try for something like this:
String.Format("{0:#,###0}", 0);
or may be like this:
string str = yourNumber.Remove(",").Replace(".",",");
Close enough tronc,
Try this snippet:
String curStr = "12.95";
Decimal decVal;
var valid = Decimal.TryParse(curStr, out decVal);
if (!valid) throw new Exception("Invalid format.");
String newFormat = decVal.ToString("C", System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"));
Within the toString(...) call, you can append a number after 'C' to specify how many decimal places should follow. E.g "C3".
This might be a very simple question.
Suppose text box show value 10,000.12 when user edits data by mistake he remove first two numbers like ,000.12 and using this textbox in the calculation then it gives an exception. I want a just validate text box.
For Example:
string str = ",100.12;"
Convert to
decimal number = 100.12;
Any Idea?.
It shows only whole number when user remove any thousand separator.
This is pretty messed up and I am not sure if all of you strings will look the same, but in case they do this might do the trick:
string str = ",0,100.12";
decimal number;
bool converted = decimal.TryParse(str.Substring(str.LastIndexOf(",") + 1), out number);
The variable converted will tell you whether or not your string was converted and you will not an exception.
Good luck!
If I understood the question, you want to remove all characters that would prevent the parse routine from failing.
string str = ",0,100.12";
var modified = new StringBuilder();
foreach (char c in str)
{
if (Char.IsDigit(c) || c == '.')
modified.Append(c);
}
decimal number= decimal.Parse(modified.ToString());
string a = "100.12";
decimal b = Convert.ToDecimal(a);
string str = ",0,100.12;";
var newstr = Regex.Replace(str,#"[^\d\.]+","");
decimal d = decimal.Parse(newstr, CultureInfo.InvariantCulture);