C # holds 2 decimal places summary of several scenarios

Source: Internet
Author: User

Scenario 1:

C # retains 2 decimal places. ToString ("F2") is OK, but if the number is three digits behind the decimal point such as 1.253, then the conversion will become 1.25. Can you just keep it to the last place, not 0?
By default, 2 bits are reserved, and if there are really 3 decimal places, 3 bits are reserved, and 4 bits are reserved for 4 bits.

Let's talk about the difference between 0 and # in ToString ("0.00##"):
0 represents the placeholder. If ToString ("0.00") preserves two decimal places, the result is two decimal places, regardless of the number of decimal places or decimals. For example 1.1234 then the result is 1.12. If it is 1.2 then the result will be 0, 1.20.
# for the back is not 0 is reserved, if it is 0 is removed. For example, ToString ("0.##") 1.20 then the result is 1.2.


For scenario 1, the default is two bits is 00, the other if the greater than two bit is not 0 is reserved, you can write the following:

Double 1.2530 ; string ret = dd. ToString ("0.00####"//  1.253

Scenario 2:

According to international practice, sometimes we need to "round" the number of digits that are exceeded. There are many ways to preserve two decimal places in C #, which are commonly summarized as follows:

1, Math.Round (0.333333,2);//According to the international standard of rounding
2, double dbdata=0.335333; String Str1=string.format ("{0:f}", dbdata);//default is two-bit reserved
3, float i=0.333333; int j= (int) (i * 100); i = j/100;
4, Decimal. Round (decimal. Parse ("0.3333333"), 2)
5, private System.Globalization.NumberFormatInfo NFI = new System.Globalization.NumberFormatInfo ();

float test=0.333333f;

Nfi. numberdecimaldigits=2;

String result=test. ToString ("N", NFI);


6, String result= String.Format ("{0:n2}", Convert.todecimal ("0.333333"). ToString ());
7, Convert.todecimal ("0.33333333"). ToString ("0.00");

C # holds 2 decimal places summary of several scenarios

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.