-
Notifications
You must be signed in to change notification settings - Fork 34
Session 03 Exercise02 Convert String to numbers #23
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
Convert String to Numbers
|
||
foreach (var number in inputArray) | ||
string numbersOnly = Regex.Replace(input, "[^0-9.,-]", ""); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Användningen av enbart detta reguljära uttrycket kan leda till oönskade effekter för användaren. Se mer detaljerad förklaring längre ner.
Om Convert.ToDouble
skall användas utan att ligga i en try
bör uttrycket vara vattentätt mot fel. Förslagsvis (^|\,)[^,]*[^0-9.,][^,]*($|\,)
som filtrerar bort hela delen mellan ,
om delen innehåller något ickenumeriskt.
Mitt förslag bör användas med Regex.Replace
"$1$2"
istället för ""
för att behålla eventuella kommatecken.
var inputArray = numbersOnly.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries); | ||
|
||
double totalValue = 0; | ||
double minValue = Convert.ToDouble(inputArray[0], System.Globalization.CultureInfo.InvariantCulture); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Om du lägger till using System.Globalization;
högst upp i filen (eller med glödlampeåtgärd), kan du skriva double minValue = Convert.ToDouble(inputArray[0], CultureInfo.InvariantCulture);
{ | ||
Console.WriteLine("Värdet är " + number); | ||
|
||
double number = Convert.ToDouble(i, System.Globalization.CultureInfo.InvariantCulture); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Notera att detta fortfarande kan bli fel eller oönskat värde med ovanstående.
Testa gärna reguljära uttryck lite via sajter som https://regex101.com/.
Betänk följande inmatade strängar: "0-9"
eller "s01e02"
, den första orsakar fel och den andra får resultatet 102. Beter sig verkligen detta program som man skulle förvänta sig?
Den enklare lösningen att helt enkelt hoppa över ett värde om det går fel med en try
-sats kan tyckas bättre.
{ | ||
maxValue = number; | ||
} | ||
if(number < minValue) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Skriv gärna mellanslag innan parentesen. if (number < minValue)
Vet inte om jag gjorde rätt med pull request men jag testar :)..