C # Decimal retains the specified number of decimal digits, not rounded

Source: Internet
Author: User

Decimal retains the specified number of decimal places. NET comes with methods that are rounded.

In the case of a project where the amount is assessed, the amount of the last Article = Total amount-The sum of the amount that has been assessed.

This may cause the last allocation to be negative, so you write a method that retains the specified number of decimal places.

The use of extension methods makes it very elegant to call them.

1  Public Static classdecimalextension2     {3         /// <summary>4         ///Decimal retains the specified number of decimal places5         /// </summary>6         /// <param name= "num" >Original Quantity</param>7         /// <param name= "scale" >number of decimal digits reserved</param>8         /// <returns>intercepts the number of digits after the specified number of decimal place strings</returns>9          Public Static stringToString ( This decimalNumintScale )Ten         { One             stringNumtostring =Num. ToString (); A  -             intindex = Numtostring.indexof ("."); -             intLength =numtostring.length; the  -             if(Index! =-1) -             { -                 return string. Format ("{0}. {1}", +Numtostring.substring (0, index), -Numtostring.substring (Index +1, Math.min (Length-index-1, scale) )); +             } A             Else at             { -                 returnNum. ToString (); -             } -         } -}
Decimal retains the specified number of decimal places

C # Decimal retains the specified number of decimal digits, not rounded

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.