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

Creating package in Oracle Database using Toad For Oracle

What are Packages in Oracle Database A package is  a group   of procedures, functions,  variables   and  SQL statements   created as a single unit. It is used to store together related objects. A package has two parts, Package  Specification  and Package Body.

Resolving 'Setup Account Privileges' error while installing SQL Server

A new installation of Microsoft SQL Server 2012 or Microsoft SQL Server 2008 R2 fails You see the following error message when you try to install a new instance of SQL Server 2012 or SQL Server 2008 R2: Rule "Setup account privileges" failed.

Creating Oracle stored Procedures using TOAD for Oracle

In a database management system, a  stored procedure  is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. The use of  stored procedures  can be helpful in controlling  access to data, preserving  data integrity  and  improving  productivity.