Summary of C decimal point formatting usage

  • 2021-11-02 02:01:15
  • OfStack

This article illustrates the use of C # decimal point formatting. Share it for your reference, as follows:

1. ToString () method


double d=12345678.2334;
Console.WriteLine(d.ToString("F2")); //1234.23
Console.WriteLine(d.ToString("###,###.00")); //12,345,678.23

2. Math. Round () method


Math.Round(3.44, 1); //Returns 3.4.
Math.Round(3.45, 1); //Returns 3.4.
Math.Round(3.46, 1); //Returns 3.5.
Math.Round(3.445, 1); //Returns 3.4.
Math.Round(3.455, 1); //Returns 3.5.
Math.Round(3.465, 1); //Returns 3.5.
Math.Round(3.450, 1); //Returns 3.4.( Complement 0 Is invalid )
Math.Round(3.4452, 2); //Returns 3.45.
Math.Round(3.4552, 2); //Returns 3.46.
Math.Round(3.4652, 2); //Returns 3.47.

"4 houses 6 into 5, after 5, if it is not zero, it will enter 1, after 5, it will look at odd and even, before 5, it should be given up, and before 5, it will enter 1."

The formula of one point shorter is called "4 houses, 6 entrances, 5 couples"

3. double. Parse () method


double d=1.12345;
d=double.Parse(d.ToString("0.00")); //1.12

4. Output percent sign


System.Globalization.NumberFormatInfo provider = new System.Globalization.NumberFormatInfo();
provider.PercentDecimalDigits = 2;// How many decimal places are reserved .
provider.PercentPositivePattern = 1;// Where does the percent sign appear .
double result = (double)1 / 3;//1 Be sure to use double Type .
Console.WriteLine(result.ToString("P", provider)); //33.33%
// Or 
Console.WriteLine((result*100).ToString("#0.#0")+"%");

5. String. Format () method


string str1 = String.Format("{0:N1}",56789); //result: 56,789.0
string str2 = String.Format("{0:N2}",56789); //result: 56,789.00
string str3 = String.Format("{0:N3}",56789); //result: 56,789.000
string str8 = String.Format("{0:F1}",56789); //result: 56789.0
string str9 = String.Format("{0:F2}",56789); //result: 56789.00
string str11 =(56789 / 100.0).ToString("#.##"); //result: 567.89
string str12 =(56789 / 100).ToString("#.##"); //result: 567

More readers interested in C # can check the topic of this site: "C # Form Operation Skills Summary", "C # Common Control Usage Tutorial", "WinForm Control Usage Summary", "C # Programming Thread Use Skills Summary", "C # Operating Excel Skills Summary", "XML File Operation Skills Summary in C #", "C # Data Structure and Algorithm Tutorial", "C # Array Operation Skills Summary" and "C # Object-Oriented Programming Introduction Tutorial"

I hope this article is helpful to everyone's C # programming.


Related articles: