Edw*_*uay 4 c# decimal rounding
以下代码目前输出:
12.1
12.100
12.1000
12.00
12
12.0000
Run Code Online (Sandbox Code Playgroud)
如何更改它以便输出:
12.1
12.1
12.1
12
12
12
Run Code Online (Sandbox Code Playgroud)
Math.Round似乎是事情,但它让我定义了我想要的小数位数,但我希望它们如上所述变量.
如果没有数学方法可以做到这一点,我只会从字符串右侧删除零和小数点,但会认为有一种数学方法来处理它.
using System;
using System.Collections.Generic;
namespace Test8834234
{
public class Program
{
static void Main(string[] args)
{
List<string> decimalsAsStrings = new List<string>
{
"12.1",
"12.100",
"12.1000",
"12.00",
"12",
"12.0000"
};
foreach (var decimalAsString in decimalsAsStrings)
{
decimal dec = decimal.Parse(decimalAsString);
Console.WriteLine(dec);
}
Console.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 10
您还可以将decimal的ToString与参数一起使用:
string s = dec.ToString("0.#");
Run Code Online (Sandbox Code Playgroud)
注意:您的代码可能存在国际化问题.你编写它的方式,它将使用用户计算机的文化信息,这可能有.小数分隔符以外的东西.这可能会导致程序为具有.千位分隔符的用户提供不正确的结果.
如果要保证parse方法始终表现相同,可以使用CultureInfo.InvariantCulture.如果您确实想根据用户的文化设置解析字符串,那么您正在做的事情很好.