decimal ToString formatting which gives at least 1 digit, no upper limit

只愿长相守 提交于 2019-12-08 20:33:37

问题


How to format a decimal in C# with at least one digit after the decimal point, but not a fixed upper limit if specified more than 1 digit after the decimal point:

5 -> "5.0"
5.1 -> "5.1"
5.122 -> "5.122"
10.235544545 -> "10.235544545"

回答1:


Use ToString("0.0###########################").

Some notes:,

  • There are 27 #s in there, as the decimal structure can accommodate precision up to 28 decimal places.
  • The 0 custom specifier will cause a digit to always be displayed, even if the value is 0.
  • The # custom specifier only displays a value if the digit is zero and all of the digits to the right/left of that digit (depending on what side of the decimal point you are on) are zero.
  • You will need to insert as many # after the first 0 to the right of the decimal point to accommodate the length of all the values you will pass to ToString, if you will only have precision to 10 decimal places, then you need nine # (since you have the first decimal place to the right handled by 0)

For more information, see the section of MSDN titled "Custom Numeric Format Strings".




回答2:


[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var a = 5m;
        var b = 5.1m;
        var c = 5.122m;
        var d = 10.235544545m;

        var ar = DecToStr.Work(a);
        var br = DecToStr.Work(b);
        var cr = DecToStr.Work(c);
        var dr = DecToStr.Work(d);

        Assert.AreEqual(ar, "5.0");
        Assert.AreEqual(br, "5.1");
        Assert.AreEqual(cr, "5.122");
        Assert.AreEqual(dr, "10.235544545");
    }
}

public class DecToStr
{
    public static string Work(decimal val)
    {
        if (val * 10 % 10 == 0)
            return val.ToString("0.0");
        else
            return val.ToString();
    }
}



回答3:


Func<decimal, string> FormatDecimal = d => (
    d.ToString().Length <= 3 || 
    !d.ToString().Contains(".")) ? d.ToString("#.0") : d.ToString()
);


来源:https://stackoverflow.com/questions/8184068/decimal-tostring-formatting-which-gives-at-least-1-digit-no-upper-limit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!