Math.Round(Convert.ToDecimal(strTemp), 2);
decimal d = Decimal.Parse("123.45678");
然后使用Round(d, m)对小数进行四舍五入,其中d是你的数字,m是小数位数,请参考http://msdn.microsoft.com/en-us/library/6be1edhb.aspx
decimal rounded = Decimal.Round(d, 2);
如果您只想进行展示性的四舍五入,可以跳过将值舍入到小数位,而是直接在输出中对值进行四舍五入:
string.Format("{0:0.00}", 123.45678m);
将该值转换为浮点数,然后进行四舍五入:
double temp = Double.Parse(strTemp, CultureInfo.InvariantCulture);
temp = Math.Round(temp, 2);
或者,如果您想要结果作为字符串,只需解析并将其格式化为两位小数:
double temp = Double.Parse(strTemp, CultureInfo.InvariantCulture);
string result = temp.ToString("N2", CultureInfo.InvariantCulture);
CultureInfo
对象的作用是使方法始终使用句点作为小数分隔符,而不考虑本地区域设置。var roundedTemp = Math.Round(decimal.Parse(strTemp), 2);
Math.Round
从什么时候开始接受字符串参数了? - Oded你可以使用这个链接http://www.csharp-examples.net/string-format-double/中的信息来处理双精度浮点数,使用double.parse API。
你可以使用数字格式信息,就像这样:
NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;
double myInt = 0.51667308807373;
// Displays the same value with four decimal digits.
nfi.NumberDecimalDigits = 2;
Console.WriteLine(myInt.ToString("N", nfi));
Console.ReadKey();