A description of the problem
In development, you need to keep the decimal type of data two decimal places after the decimal point and do not need to be rounded, that is, directly intercept the two decimal places after the decimal point. Example:1.245M--1.24, not 1.25
You can use the decimal.round () method to preserve several decimal places after the decimal of the decimal type data, but the method will be rounded instead of directly intercepted. Therefore, this method is not advisable, search on the internet and did not find a suitable method, they have implemented a truncated decimal type data decimal point after a number of methods.
Two detailed implementation code
Using system;namespace cutdecimal{public static class Decimalhelper {public static decimal Cutdecimalwithn (decimal d, int n) { string strdecimal = D.tostring (); int index = Strdecimal.indexof ("."); if (index = =-1 | | Strdecimal.length < INDEX + n + 1) { Strdecimal = string. Format ("{0:f" + n + "}", D); } else { int length = index; if (n! = 0) { length = index + n + 1; } Strdecimal = strdecimal.substring (0, length); } return Decimal.Parse (Strdecimal);}}
Three test codes and results
static void Main (string[] args) { decimal d = 1.23456789M; for (int i = 0; I <=; i++) { Console.WriteLine ("{0}", Decimalhelper.cutdecimalwithn (d, i)); } for (int i = 0; I <=; i++) { Console.WriteLine ("{0}", Decimal.round (d, i));} }
in the test code, not only the test code of the implementation method in this paper is given, but also the test code of the Decimal.round () method, and the result is as shown in the final operation.
Figure 1 running results
Can you see the difference, folks?
Keep decimal type data in n decimal places without rounding (C #)