Home
C#
Math.Truncate Use
Updated Aug 6, 2021
Dot Net Perls
Math.Truncate. This C# method eliminates numbers after the decimal. It acts upon a decimal or floating-point number, calculating the integral part of a number.
C# method notes. Math.Truncate is reliable and easy to use. Its functionality differs from Math.Round. Sometimes casting to int can truncate a number effectively as well.
Example. This program calls the Math.Truncate method on a decimal and double. The Math.Truncate overloads called in this program are implemented differently in .NET.
decimal
Info You can see that the decimal 1.223 was truncated to 1, and the double 2.913 was truncated to 2.
Also The value 2.9 is not rounded up to 3. You would want Math.Round for this functionality.
Math.Round
using System; class Program { static void Main() { decimal a = 1.223M; double b = 2.913; // Truncate the decimal and double, receiving new numbers. decimal result1 = Math.Truncate(a); double result2 = Math.Truncate(b); // Print the results. Console.WriteLine(result1); Console.WriteLine(result2); } }
1 2
Discussion. There are some other ways you can truncate numbers. If you have a double value and cast it to an int, you can erase all the values past the decimal place.
Info This is an optimization, but it does not always work. You must be careful to only use casting where it yields the correct result.
Cast
Detail This version would fail in certain cases such as with large doubles. In other cases it would be faster.
double
// These two statements sometimes provide the same result. b = Math.Truncate(b); b = (double)(int)b;
Summary. We explored the Math.Truncate method. This method erases all the numbers past the decimal place in a double or decimal number type.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Aug 6, 2021 (new example).
Home
Changes
© 2007-2025 Sam Allen