[.net] Truncate Decimal number not Round Off

Possible Duplicate:
c# - How do I round a decimal value to 2 decimal places (for output on a page)

I want to truncate the decimals like below

i.e.

  • 2.22939393 -> 2.229
  • 2.22977777 -> 2.229

This question is related to .net floating-point truncate

The answer is


This is similar to TcKs suggestion above, but using math.truncate rather than int conversions

VB: but you'll get the idea

Private Function TruncateToDecimalPlace(byval ToTruncate as decimal, byval DecimalPlaces as integer) as double 
dim power as decimal = Math.Pow(10, decimalplaces)
return math.truncate(totruncate * power) / power
end function

Try this:

decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together

It can be writen shorter, but this is more descriptive.

EDIT: Short way:

decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));

Here's an extension method which does not suffer from integer overflow (like some of the above answers do). It also caches some powers of 10 for efficiency.

static double[] pow10 = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10 };
public static double Truncate(this double x, int precision)
{
    if (precision < 0)
        throw new ArgumentException();
    if (precision == 0)
        return Math.Truncate(x);
    double m = precision >= pow10.Length ? Math.Pow(10, precision) : pow10[precision];
    return Math.Truncate(x * m) / m;
}

Try this:

decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together

It can be writen shorter, but this is more descriptive.

EDIT: Short way:

decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));

This is similar to TcKs suggestion above, but using math.truncate rather than int conversions

VB: but you'll get the idea

Private Function TruncateToDecimalPlace(byval ToTruncate as decimal, byval DecimalPlaces as integer) as double 
dim power as decimal = Math.Pow(10, decimalplaces)
return math.truncate(totruncate * power) / power
end function

You can use Math.Round:

decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229

Or you can use ToString with the N3 numeric format.

string roundedNumber = number.ToString("N3");

EDIT: Since you don't want rounding, you can easily use Math.Truncate:

Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229

What format are you wanting the output?

If you're happy with a string then consider the following C# code:

double num = 3.12345;
num.ToString("G3");

The result will be "3.12".

This link might be of use if you're using .NET. http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

I hope that helps....but unless you identify than language you are using and the format in which you want the output it is difficult to suggest an appropriate solution.


Maybe another quick solution could be:

>>> float("%.1f" % 1.00001)
1.0
>>> float("%.3f" % 1.23001)
1.23
>>> float("%.5f" % 1.23001)
1.23001

Try this

double d = 2.22912312515;
int demention = 3;
double truncate = Math.Truncate(d) + Math.Truncate((d - Math.Truncate(d)) * Math.Pow(10.0, demention)) / Math.Pow(10.0, demention);

Forget Everything just check out this

double num = 2.22939393;
num  = Convert.ToDouble(num.ToString("#0.000"));

What format are you wanting the output?

If you're happy with a string then consider the following C# code:

double num = 3.12345;
num.ToString("G3");

The result will be "3.12".

This link might be of use if you're using .NET. http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

I hope that helps....but unless you identify than language you are using and the format in which you want the output it is difficult to suggest an appropriate solution.


Here's an extension method which does not suffer from integer overflow (like some of the above answers do). It also caches some powers of 10 for efficiency.

static double[] pow10 = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10 };
public static double Truncate(this double x, int precision)
{
    if (precision < 0)
        throw new ArgumentException();
    if (precision == 0)
        return Math.Truncate(x);
    double m = precision >= pow10.Length ? Math.Pow(10, precision) : pow10[precision];
    return Math.Truncate(x * m) / m;
}

You can use Math.Round:

decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229

Or you can use ToString with the N3 numeric format.

string roundedNumber = number.ToString("N3");

EDIT: Since you don't want rounding, you can easily use Math.Truncate:

Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229

Forget Everything just check out this

double num = 2.22939393;
num  = Convert.ToDouble(num.ToString("#0.000"));

A function to truncate an arbitrary number of decimals:

public decimal Truncate(decimal number, int digits)
{
  decimal stepper = (decimal)(Math.Pow(10.0, (double)digits));
  int temp = (int)(stepper * number);
  return (decimal)temp / stepper;
}

Maybe another quick solution could be:

>>> float("%.1f" % 1.00001)
1.0
>>> float("%.3f" % 1.23001)
1.23
>>> float("%.5f" % 1.23001)
1.23001

You can use Math.Round:

decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229

Or you can use ToString with the N3 numeric format.

string roundedNumber = number.ToString("N3");

EDIT: Since you don't want rounding, you can easily use Math.Truncate:

Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229

You can use Math.Round:

decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229

Or you can use ToString with the N3 numeric format.

string roundedNumber = number.ToString("N3");

EDIT: Since you don't want rounding, you can easily use Math.Truncate:

Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229

A function to truncate an arbitrary number of decimals:

public decimal Truncate(decimal number, int digits)
{
  decimal stepper = (decimal)(Math.Pow(10.0, (double)digits));
  int temp = (int)(stepper * number);
  return (decimal)temp / stepper;
}

Try this

double d = 2.22912312515;
int demention = 3;
double truncate = Math.Truncate(d) + Math.Truncate((d - Math.Truncate(d)) * Math.Pow(10.0, demention)) / Math.Pow(10.0, demention);

Try this:

decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together

It can be writen shorter, but this is more descriptive.

EDIT: Short way:

decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));

What format are you wanting the output?

If you're happy with a string then consider the following C# code:

double num = 3.12345;
num.ToString("G3");

The result will be "3.12".

This link might be of use if you're using .NET. http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

I hope that helps....but unless you identify than language you are using and the format in which you want the output it is difficult to suggest an appropriate solution.


Try this:

decimal original = GetSomeDecimal(); // 22222.22939393
int number1 = (int)original; // contains only integer value of origina number
decimal temporary = original - number1; // contains only decimal value of original number
int decimalPlaces = GetDecimalPlaces(); // 3
temporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer
temporary = (int)temporary; // removes all decimal places
temporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places
decimal result = original + temporary; // add integer and decimal places together

It can be writen shorter, but this is more descriptive.

EDIT: Short way:

decimal original = GetSomeDecimal(); // 22222.22939393
int decimalPlaces = GetDecimalPlaces(); // 3
decimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to floating-point

Convert list or numpy array of single element to float in python Convert float to string with precision & number of decimal digits specified? Float and double datatype in Java C convert floating point to int Convert String to Float in Swift How do I change data-type of pandas data frame to string with a defined format? How to check if a float value is a whole number Convert floats to ints in Pandas? Converting Float to Dollars and Cents Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Examples related to truncate

Scala Doubles, and Precision Truncating Text in PHP? How can I truncate a double to only two decimal places in Java? SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES How to truncate a foreign key constrained table? Remove the last line from a file in Bash I want to truncate a text or line with ellipsis using JavaScript Limiting double to 3 decimal places I got error "The DELETE statement conflicted with the REFERENCE constraint" Truncate with condition