C # decimal retains the specified decimal places,

Source: Internet
Author: User

C # decimal retains the specified decimal places,

When decimal retains the specified decimal digits, the. NET method is rounding.

If the project encounters a apportioned amount, the amount in the last line = total amount-sum of the apportioned amount.

This may result in a negative number when the last part is apportioned. Therefore, I wrote a method to retain the decimal digits of the specified number.

The use of extension methods makes calling very elegant.

1 public static class DecimalExtension 2 {3 /// <summary> 4 /// decimal keep the specified number of digits 5 /// </summary> 6 /// <param name =" num "> original quantity </param> 7 // <param name =" scale "> retain decimal places </param> 8 /// <returns> after the specified decimal places are intercepted number of strings </returns> 9 public static string ToString (this decimal num, int scale) 10 {11 string numToString = num. toString (); 12 13 int index = numToString. indexOf (". "); 14 int length = numToString. length; 15 16 if (index! =-1) 17 {18 return string. format ("{0 }. {1} ", 19 numToString. substring (0, index), 20 numToString. substring (index + 1, Math. min (length-index-1, scale); 21} 22 else23 {24 return num. toString (); 25} 26} 27}
Decimal reserved decimal digits

 

Related Article

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.