我想用数学来做。圆的函数


当前回答

字符串a = "10.65678";

decimal d = Math.Round(Convert.ToDouble(a.ToString()),2)

其他回答

//转换到小数点后两位

String.Format("{0:0.00}", 140.6767554);        // "140.67"
String.Format("{0:0.00}", 140.1);             // "140.10"
String.Format("{0:0.00}", 140);              // "140.00"

Double d = 140.6767554;
Double dc = Math.Round((Double)d, 2);       //  140.67

decimal d = 140.6767554M;
decimal dc = Math.Round(d, 2);             //  140.67

= = = = = = = = =

// just two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"

也可以将“0”和“#”组合。

String.Format("{0:0.0#}", 123.4567)       // "123.46"
String.Format("{0:0.0#}", 123.4)          // "123.4"
String.Format("{0:0.0#}", 123.0)          // "123.0"

就我个人而言,我从来没有四舍五入过。让它尽可能坚定,因为舍入在CS中是一个转移注意力的东西。但您确实希望为用户格式化数据,为此,我发现string.Format("{0:0.00}", number)是一种很好的方法。

试试这个:

twoDec = Math.Round(val, 2)

字符串a = "10.65678";

decimal d = Math.Round(Convert.ToDouble(a.ToString()),2)

下面是一些例子:

decimal a = 1.994444M;

Math.Round(a, 2); //returns 1.99

decimal b = 1.995555M;

Math.Round(b, 2); //returns 2.00

你可能还想看看银行家的四舍五入/四舍五入到偶数与以下过载:

Math.Round(a, 2, MidpointRounding.ToEven);

这里有更多的信息。