M.hjespersen M.hjespersen - 2 months ago 5
C# Question

c# do-while loop not working as I need it to

I want my loop to repeat as long as width is under 0.5 (MIN_WIDTH) or above 5.0 (MAX_WIDTH) both are created as constant doubles.
When I write the number 0, it does repeat as it should, but if I write anything between 0.1 - 0.4 it skips the loop, why?

do
{
Console.Write("Give the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + " :");
widthString = Console.ReadLine();
width = double.Parse(widthString);
} while (width < MIN_WIDTH || width > MAX_WIDTH);

Answer

It seems that you experience problems with decimal and thousand separators: if in your current culture (e.g. in Russian RU-ru one) . is a thousand (not decimal) separator it ignores and you'll get 0.4 -> 04 -> 4 which will pass the condition.

Remedy: specify CultureInfo.InvariantCulture explictly

do {
  Console.Write($"Give the width of the window between {MIN_WIDTH} and {MAX_WIDTH}: ");
  widthString = Console.ReadLine();

  double width;

  if (!double.TryParse(widthString, 
                       NumberStyles.Any, 
                       CultureInfo.InvariantCulture, 
                       out width))
    continue;
} while (width < MIN_WIDTH || width > MAX_WIDTH);
Comments