C#:由 Random 组成的 var 的四舍五入小数

C#: Round decimals for var made of Random

我明白了(C#):

Random RNG = new Random();
decimal divab50 = RNG.Next(50,100);
decimal divbl50 = RNG.Next(6,50);
decimal decreturn = divab50 / divbl50;
Console.WriteLine(decreturn);

如何将递减变量四舍五入到两位小数?我试过 Math.Round 和 String.Format 它们似乎不适用于 RNG 中生成的变量。我认为。我是 c# 的新手,刚开始

如果您使用变量 decreturn 并执行 Math.Round(decreturn, 2)String.Format("{0:F2}", decreturn),它会按预期工作。

以下示例有效:

using System;

public class Program
{
    public static void Main()
    {
        Random RNG = new Random();
        decimal divab50 = RNG.Next(50,100);
        decimal divbl50 = RNG.Next(6,50);
        decimal decreturn = divab50 / divbl50;
        decimal rounded = Math.Round(decreturn, 2);
        Console.WriteLine(rounded);
    }
}

Fiddle 使用 Math.Round 进行测试:https://dotnetfiddle.net/70LTrm

您也可以为此目的申请 String.Format,如下所示:

using System;

public class Program
{
    public static void Main()
    {
        Random RNG = new Random();
        decimal divab50 = RNG.Next(50,100);
        decimal divbl50 = RNG.Next(6,50);
        decimal decreturn = divab50 / divbl50;
        var rounded = String.Format("{0:F2}", decreturn);
        Console.WriteLine(rounded);
    }
}

Fiddle 使用 String.Format 进行测试:https://dotnetfiddle.net/6Yy8uU

查看 Math.Round and String.Format 的文档了解更多信息。

根据需要使用Math.Round or an appropriate format specifier

Rounds a double-precision floating-point value to a specified number of fractional digits, and rounds midpoint values to the nearest even number.

The fixed-point ("F") format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative.

The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the current NumberFormatInfo.NumberDecimalDigits property supplies the numeric precision.

// this should be a static or an instance field
Random RNG = new Random();

// inside a method
decimal divab50 = RNG.Next(50,100);
decimal divbl50 = RNG.Next(6,50);
decimal decreturn = divab50 / divbl50;
Console.WriteLine(Math.Round(decreturn,2));
Console.WriteLine($"{decreturn:F2}");   

示例输出

3.42
3.42

Online Demo

注意 :每次需要随机数时创建 Random 的新实例会导致问题。最好将其用作 static 字段或实例成员

谢谢大家的回答。

对我有用的是将“{0:F2}”添加到 WriteLine 方法中,如下所示:

Random RNG = new Random();
decimal divab50 = RNG.Next(50,100);
decimal divbl50 = RNG.Next(6,50);
decimal decreturn = divab50 / divbl50;
Console.WriteLine("{0:F2}",decreturn);

这也奏效了。我第一次做的不对。

decimal rounded = Math.Round(decreturn, 2);
Console.WriteLine(rounded);

谢谢大家