marwan akhandaf marwan akhandaf - 1 month ago 16
C# Question

How to convert int to a decimal with comma?

Console.Write("Hoeveel worpen wil je simuleren: ");
int worpen = int.Parse(Console.ReadLine());



Random r = new Random(worpen);
int willekeur = r.Next(1, worpen);
double willekeur1 = willekeur;
Math.Round(willekeur1);


for (int i = 1; i <= 12; i++)
{
Console.WriteLine("ik gooide "+willekeur+" ("+Math.Round(willekeur1,2,)+")");
willekeur = r.Next(1, worpen);

}
Console.ReadLine();


I want that ' willekeur1 ' a number which contains a decimal comma is. so example: 12456--> 12,456

Answer

this might be useful for you:

public float ReadFloat()
        {
            float ReadValue = 0;
            string KeySequence = "";
            string TempKey = "";
            bool CommaUsed = false;
            ConsoleKeyInfo key;
            do
            {
                key = Console.ReadKey(true);
                if ((key.Key >= ConsoleKey.D0 && key.Key <= ConsoleKey.D9) || (key.Key >= ConsoleKey.NumPad0 && key.Key <= ConsoleKey.NumPad9))
                {
                    TempKey = Convert.ToString(key.Key);
                    TempKey = TempKey.Remove(0, 1);
                    KeySequence += TempKey;
                    Console.Write(TempKey);
                };

                if (key.Key == ConsoleKey.OemComma || key.Key == ConsoleKey.Decimal)
                {
                    if (!CommaUsed)
                    {
                        KeySequence += ".";
                        Console.Write(".");
                        CommaUsed = true;

                    };
                };

                if ((key.Key == ConsoleKey.Backspace) && KeySequence != "")
                {
                    string LastChar = KeySequence.Substring(KeySequence.Length - 1);
                    //MessageBox.Show("Last char: "+LastChar);
                    //Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)
                    char SepDeci = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
                    if (Convert.ToChar(LastChar) == SepDeci)
                    {
                        CommaUsed = false;
                    };
                    KeySequence = KeySequence.Remove(KeySequence.Length - 1);
                    Console.Write("\b \b");
                };
            }
            while (key.Key != ConsoleKey.Enter);
            if (KeySequence == "")
            {
                return 0;
            };
            ReadValue = Convert.ToSingle(KeySequence);
            return ReadValue;
        }

this method reads value from console but allows only numbers and one decimal separator (comma or dot, depending on your culture settings). to use is to read value to a variable:

willekeur1 = ReadFloat();