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.
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.
// 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).