使用Math.Round在C#中舍入浮点数

时间:2015-01-27 16:12:16

标签: c# floating-point rounding

https://github.com/TelerikAcademy/CSharp-Part-1/blob/master/4.%20Console%20In%20and%20Out/README.md

问题3,这是我的代码:

Console.Write("Please enter circle radius: ");
double Radius = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("\nPerimeter is: {0:F2}", Math.PI*2*Radius);
Console.WriteLine("Area is: {0:F2}", Math.PI*Radius*Radius);

问题5,这是我的代码:

Console.Write("Enter first number: ");
int a = Convert.ToInt32(Console.ReadLine());

if (a<0 || a>500)
{
    Console.WriteLine("number A out of bounds!");
    Environment.Exit(0);
}

Console.Write("Enter second number: ");
float b = Convert.ToSingle(Console.ReadLine());

Console.Write("Enter third number: ");
float c = Convert.ToSingle(Console.ReadLine());

string ahex = a.ToString("X");
string abin = Convert.ToString(a, 2);
abin = abin.PadLeft(10,'0');

//float brounded = Math.Round(b,2);

//float crounded = Math.Round(c,3);

Console.WriteLine(ahex + " |" + abin + "| " + "{0:0.00}|" + "{1:0.000} |", b, c);

出于某种原因,在问题5中我尝试使用我在问题3中使用的{0:2F}格式,输出将我的float转换为十六进制表示法。这没有任何意义。因此,我必须使用{0:0.00}格式。出了什么问题?

1 个答案:

答案 0 :(得分:1)

根据MSDN Standard numeric Formatting

,它应为F2