. Net decimal retains the specified decimal places (not rounded),. netdecimal

Source: Internet
Author: User

. Net decimal retains the specified decimal places (not rounded),. netdecimal

Preface

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.

Sample Code

Public static class DecimalExtension {// <summary> // decimal retains the specified number of digits in decimal places /// </summary> /// <param name = "num"> original quantity </param> /// <param name = "scale"> retain decimal places </param> /// <returns> truncates the number of strings after the specified decimal places </returns> public static string ToString (this decimal num, int scale) {string numToString = num. toString (); int index = numToString. indexOf (". "); int length = numToString. length; if (index! =-1) {return string. format ("{0 }. {1} ", numToString. substring (0, index), numToString. substring (index + 1, Math. min (length-index-1, scale);} else {return num. toString ();}}}

Summary

The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.

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.