c# - Fixing a System.FormatException -
i writing code @ group in text file called a, , if line in code contains phrase "savings found" write out line, , if has 30% or more savings place asterisk in front , if contains 30% or more , has $500 or more savings, place 2 asterisks. below have sample data, example of console needs like, , code have far:
string find = "savings found:"; foreach (var line in a.where(w => w.contains(find))) { var substr = line.substring(line.indexof(find) + find.length); var startindex = substr.indexof('('); var endindex = substr.indexof(')'); var savings = double.parse(substr.substring(0, startindex - 1).trim()); var percent = double.parse(substr.substring(startindex + 1, endindex - startindex - 2).trim()); console.writeline("{0}{1}{2}", (percent >= 30) ? "*" : string.empty, (percent >= 30 && savings >= 500) ? "*" : string.empty, line); } sample data/example
* 5/21/2015 11:55:56 pm | batch 6|386/767|50.33 %|ch2m-r|processed nxrmn5...checking refundable , non-refundable fares. traditional booking. inside ticketing window. minimum savings required: $131.00. actual savings: $257.18. savings found: $257.18 (11.55 %). savings found. the problem having getting formatexception error, , think know problem is. problem value of substring 257.18 , after that. don't want after want number. can rid of junk can compile?
this problem similar previous question asked, in answer argumentindexoutofbounds exception, tried fix it, did not go far in fixing problem, hence reasoning behind question.
you can use regex that:
foreach(string line in a) { match m = regex.match(line, @"savings\s+found:\s*\$(?<savings>\d+\.\d+)\s*\(\s*(?<percent>\d+\.\d+)\s*%"); if (m.success) { decimal savings = decimal.parse(m.groups["savings"].value, cultureinfo.invariantculture); decimal percent = decimal.parse(m.groups["percent"].value, cultureinfo.invariantculture); string prefix = string.empty; if (percent >= 30) { if (savings >= 500) prefix = "**"; else prefix = "*"; } console.writeline(prefix + line); } }
Comments
Post a Comment