Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法显示正确的十进制数_C#_.net - Fatal编程技术网

C# 无法显示正确的十进制数

C# 无法显示正确的十进制数,c#,.net,C#,.net,我必须为我的学校项目创建一个简单的数字舍入工具。 它允许用户决定给定数字的整数位数 我无法让我的代码将用户的输入(number)四舍五入到给定的小数(decimalamount) 它只是每次显示默认的2位小数:( 任何帮助都将不胜感激 static void Main(string[] args) { Console.Clear(); while (true) { string input; decimal number;

我必须为我的学校项目创建一个简单的数字舍入工具。
它允许用户决定给定数字的整数位数

我无法让我的代码将用户的输入(
number
)四舍五入到给定的小数(
decimalamount

它只是每次显示默认的2位小数:( 任何帮助都将不胜感激

static void Main(string[] args)
{
    Console.Clear();
    while (true)
    {
        string input;
        decimal number;
        int decimalammount;

        Console.WriteLine("Rounderuperer");
        Console.WriteLine("Please enter the number you wish to round:");
        input = Console.ReadLine();
        number = decimal.Parse(input);
        Console.WriteLine("Please enter the number of decimals you wish to round to:");
        input = Console.ReadLine();
        decimalammount = int.Parse(input);
        Console.WriteLine("{0:f} Rounded to {1:g} decimals = {2:f}", number, decimalammount, Math.Round(number, decimalammount, MidpointRounding.AwayFromZero));
        Console.WriteLine("Press <Spacebar> to round another number . . .");
        if (Console.ReadKey().Key != ConsoleKey.Spacebar)
            break;

    }
}
static void Main(字符串[]args)
{
Console.Clear();
while(true)
{
字符串输入;
十进制数;
整数分贝数;
控制台写入线(“Rounderuperer”);
Console.WriteLine(“请输入要舍入的数字:”);
input=Console.ReadLine();
number=decimal.Parse(输入);
Console.WriteLine(“请输入要舍入的小数位数:”);
input=Console.ReadLine();
decimalamount=int.Parse(输入);
WriteLine(“{0:f}四舍五入到{1:g}小数={2:f}”,number,decimalamount,Math.Round(number,decimalamount,middpointrounding.AwayFromZero));
Console.WriteLine(“按以舍入另一个数字…”);
if(Console.ReadKey().Key!=ConsoleKey.Spacebar)
打破
}
}

您的问题是数字格式的
f
。说明如下:

“F”或“F”定点结果:带可选负号的整数和十进制数字。
支持:所有数字类型。
精度说明符:小数位数。
默认精度说明符:由NumberFormatInfo.NumberDecimalDigits定义

委员会:

在数值中使用的小数位数。不变量信息的默认值为2

这就是为什么你总是得到小数点后2位的原因

最简单的解决方案是完全删除格式。实际上也是在第一个数字中,因为您可能希望它与所有小数一起显示

Console.WriteLine("{0} Rounded to {1:g} decimals = {2}", number, decimalammount, Math.Round(number, decimalammount, MidpointRounding.AwayFromZero));

请为您的输入和期望的输出添加一个示例。您面临的具体问题是什么?上面的代码是否产生错误?如果是,您的输入和预期结果是什么?欢迎来到stackoverflow。您的帖子对于一个新的贡献者来说是非常好的。如果您能够按照以下内容编写一些东西,那么它将变得完美:“如果我输入数字2.123456并输入4作为小数位数,我得到的输出是2.12。但我希望它是2.1235”使用以下命令:Console.WriteLine(“{0}四舍五入到{1:g}小数={2}”,number,decimalamount,Math.Round(number,decimalamount,middpointrounding.AwayFromZero)。ToString());非常感谢大家的帮助,如果我的问题写得不好,我很抱歉!非常感谢Mong Zhu,你的回答非常翔实,谢谢!!