如何用逗号将int转换为小数
本文关键字:转换 小数 int 何用逗 | 更新日期: 2023-09-27 18:16:13
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();
我希望' willekeur1 '是一个包含小数逗号的数字。例如:12456-> 12456
你可以这样做:(你需要最新的c#使用字符串插值)
$"{12456:n0}"; // 12,456
$"{12456:n2}"; // 12,456.00
在你的情况下
Console.WriteLine($"ik gooide {willekeur} ({Math.Round(willekeur1,2,)})");
或
$"{Math.Round(willekeur1,2):n0}";
$"{Math.Round(willekeur1,2):n2}";
这可能对你有用:
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;
}
此方法从控制台中读取值,但只允许数字和一个小数分隔符(逗号或点,取决于您的区域性设置)。使用是读取值到一个变量:
willekeur1 = ReadFloat();