Decimal ToString formatting that gives at least 1 digits, with no upper limit

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

 5 -> "5.0" 5.1 -> "5.1" 5.122 -> "5.122" 10.235544545 -> "10.235544545" 
+6
source share
3 answers

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

Some notes :,

  • There is 27 # , since the decimal structure can accommodate accuracy up to 28 decimal places.
  • 0 custom specifier will always display a digit, even if the value is 0.
  • # custom specifier only displays the value if the digit is zero, and all digits to the right / left of this digit (depending on which side of the decimal point you are on) are zero.
  • You will need to insert as many # as possible after the first 0 right of the decimal point to place the length of all the values ​​that you will go to ToString , if you only have precision up to 10 decimal places, then you will need nine # (since you have first decimal place on the right side 0 )

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

+12
source
 [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(); } } 
+2
source
 Func<decimal, string> FormatDecimal = d => ( d.ToString().Length <= 3 || !d.ToString().Contains(".")) ? d.ToString("#.0") : d.ToString() ); 
0
source

All Articles