如何舍入字符串中的两位小数?
可能重复:
c# – 如何将十进制值舍入到2个小数位(用于页面上的输出)
string strTemp = "0.51667308807373";
通过舍入两位小数来转换为十进制。
Math.Round(Convert.ToDecimal(strTemp), 2);
首先将字符串转换为十进制(使用Decimal.Parse或Decimal.TryParse)。
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);
您可能需要检查以确保字符串始终是小数,但认为这是它的本质。
您可以使用此链接中的信息http://www.csharp-examples.net/string-format-double/获取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();
- Repeater中的DropDownList:如何处理SelectedIndexChange并获取DataItem?
- 货币兑换
- 是什么让Entity Framework / Upshot相信我的对象图“包含周期”?
- ASPNETCOMPILER(0,0):错误ASPRUNTIME:对象引用未设置为对象的实例
- SqlDependency.Start(connectionString)每次返回false
- 如何获取当前用户的Windows身份
- 是否可以创建自定义ASP.NET MVC强类型HTML帮助程序?
- 使用webservices API确定用户在SharePoint站点/工作区中的角色
- 代码Behing更新web.config映射问题