c# - 如何将字符串转换为带尾随零的十进制

标签 c#

假设我们有 stringvalue=125.32600 用这段代码转换成十进制值

decimal d;
decimal.tryparse(stringvalue,out d)

d值为125.326 我怎样才能将最终结果转换为 125.32600

最佳答案

你不能,因为 125.32600 等于 125.326。但是,在这种情况下,我猜您想以特定格式打印出来,可以这样做:

Console.WriteLine(d.ToString("f5"));

阅读Standard Numeric Format Strings

更新

扩展方法:

public string Format(this decimal source, int precision)
{
    if (precision < 0)
    {
        throw new ArgumentOutOfRangeException("Precision must be a non negative integer");
    }

    return source.ToString("f" + precision);
}

可以这样使用:

Console.WriteLine(d.Format(5));

关于c# - 如何将字符串转换为带尾随零的十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19196873/

相关文章:

c# - 如何使用 C# 在没有任何循环的情况下打印 1 到 100

c# - Convert.ToInt32 - 保持前导零

c# - 使用 EPPlus 将图像添加到 Excel

c# - 在 C# 中验证数字签名

c# - 有没有办法使用 LINQ 将重复项目的集合与其子集合合并?

c# - 如何使用 OpenCVSharp 将 Mat 转换为 Bitmap?

c# - ASP.NET MVC : How can I change the role of an user?

c# - 如何使用 NHibernate 上传大文件?

c# - 单击事件处理程序问题

c# - Localhost 在 Windows 上的表现更好吗?