无法显示正确的小数位数

拉格兹

我必须为我的学校项目创建一个简单的数字舍入工具。
它使用户可以确定要舍入给定数字的小数位数。

我无法获取将用户输入(number舍入到给定小数(decimalammount)的代码。

每次都只显示默认的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;

    }
}
Mong Zhu

您的问题是f数字的格式。数字格式字符串文档中说明以下内容:

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

NumberFormatInfo.NumberDecimalDigit文档告诉我们

数值中使用的小数位数。InvariantInfo的默认值为2。

因此,这就是为什么总是获得小数点后两位的原因。

最简单的解决方案是完全删除格式。实际上也是第一个数字,因为您可能希望将其所有小数点都显示出来

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章