Skip to main content

Truncating specific decimal places without rounding in c#

While writing programs sometimes we will come across to display decimal number with specific precisions only even if we are getting decimal number with more number of precisions.



Suppose a scenario where I am getting decimal value from database or some where else like 100.456789 and i want to display this as 100.456 by truncating last 789 digits on my UI.

So here if we apply Math.Round() function for 3 decimal places then that will round decimal number like 100.457. here 7 is greater than 5 so it will add one in adjacent. If i don't want to be added that number to its adjucent then I have to go for truncate numbers.

So this can be achieved in two ways:
1. Math.Truncate function.
2. String Formatting.

1. Using Math.Truncate() function:

decimal inputNumber = 100.456789;
decimal truncatedNumber = Math.Truncate(inputNumber*1000)/100;

these line of code will give us 100.456

2. Using String Formatting:

if(inputNumber.ToString().Contain('.'))
{
     string[] inputArr =  inputNumber.ToString();

     if(inputArr.Length==2)
    {
      if(inputArr[1].Length > 3)
      {
          string output = inputNumber.ToString().Substring(0inputNumber.ToString().LastIndexOf(".").Length + 3);

       //now here we just need to convert string number to decimal type something like below
      decimal returnValue = decimal.Parse(string.Format("{0:0.###}", output)); 

       }
    }
}


I hope this code snippet will be helpful.....

Popular posts from this blog

Asp.Net Web API

What is ASP.NET Web API? ASP.NET Web API is a framework provided by the Microsoft with which we can easily build HTTP services that can reach a broad of clients, including browsers, mobile, IoT devices, etc. ASP.NET Web API provides an ideal platform for building RESTful applications on the .NET Framework.   Difference between ASP.NET Web API and WCF Web AP I is a Framework to build HTTP Services that can reach a board of clients, including browsers, mobile, IoT Devices, etc. and provided an ideal platform for building RESTful applications. It is limited to HTTP based services. ASP.NET framework ships out with the .NET framework and is Open Source. WCF i.e. Windows Communication Foundation is a framework used for building Service Oriented applications (SOA) and supports multiple transport protocol like HTTP, TCP, MSMQ, etc. It supports multiple protocols like HTTP, TCP, Named Pipes, MSMQ, etc. WCF ships out with the .NET Framework. Both Web API and WCF can be self-hosted or can be...