I need to truncate the number to two decimal places, which basically means reducing extra digits.
For instance:
2.919 -> 2.91 2.91111 -> 2.91
Why? This is what SQL Server does when storing a few extra precision. For example, if the column is Decimal (8.2) and you are trying to insert / update the number 9.1234, 3 and 4 will be chopped off.
I need to do the same in C # code.
The only possible ways that I can think of are either:
Using stringformatter to βprintβ only two decimal places, and then converting it to decimal, for example:
decimal tooManyDigits = 2.1345 decimal ShorterDigits = Convert.ToDecimal(tooManyDigits.ToString("0.##"));
I am not happy with this because it includes a string, and then another string to decimal conversion, which seems a little crazy.
Using Math.Truncate (which only accepts an integer), so I can multiply it by 100, truncate it, and then divide by 100. For example:
decimal tooLongDecimal = 2.1235; tooLongDecimal = Math.Truncate(tooLongDecimal * 100) / 100;
I am also not happy with this, because if tooLongDecimal is 0, I will get a division error by 0.
Of course there is a better + easier way! Any suggestions?
source share