It turns out that writing \r
to the console will move the cursor to the beginning of the line the user is typing into. So as he types I can store the entered number so far, and overwrite what he's typing with the formatted number.
This could cause problems when he presses Backspace, so in that situation I just print many spaces to erase what was previously entered, and display the new number again.
The method returns when the user presses Enter, and only if he had entered at least one digit.
public static long ReadNumberAndFormat()
{
var numberString = "";
long number = 0;
while (true)
{
var keyInfo = Console.ReadKey();
if (keyInfo.Key == ConsoleKey.Enter)
{
if (numberString.Length > 0)
{
break;
}
else
{
continue;
}
}
if (keyInfo.Key == ConsoleKey.Backspace && numberString.Length > 0)
{
numberString = numberString.Remove(numberString.Length - 1);
Console.Write("\r ");
}
else
{
numberString += keyInfo.KeyChar;
}
if (long.TryParse(numberString, out number))
{
Console.Write('\r' + number.ToString("n0"));
}
}
return number;
}