Math.Truncate Use
This page was last reviewed on 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.
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.
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, Int
Detail This version would fail in certain cases such as with large doubles. In other cases it would be faster.
// 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 6, 2021 (new example).
© 2007-2024 Sam Allen.