[c#] Limiting double to 3 decimal places

This i what I am trying to achieve:

If a double has more than 3 decimal places, I want to truncate any decimal places beyond the third. (do not round.)

Eg.: 12.878999 -> 12.878

If a double has less than 3 decimals, leave unchanged

Eg.:   125   -> 125
       89.24 -> 89.24

I came across this command:

double example = 12.34567;
double output = Math.Round(example, 3);

But I do not want to round. According to the command posted above, 12.34567 -> 12.346

I want to truncate the value so that it becomes: 12.345

This question is related to c# double truncate

The answer is


double example = 3.1416789645;
double output = Convert.ToDouble(example.ToString("N3"));

In C lang:

double truncKeepDecimalPlaces(double value, int numDecimals)
{
    int x = pow(10, numDecimals);
    return (double)trunc(value * x) / x;
}

Multiply by 1000 then use Truncate then divide by 1000.


You can use:

double example = 12.34567;
double output = ( (double) ( (int) (example * 1000.0) ) ) / 1000.0 ;

Good answers above- if you're looking for something reusable here is the code. Note that you might want to check the decimal places value, and this may overflow.

public static decimal TruncateToDecimalPlace(this decimal numberToTruncate, int decimalPlaces)
{
    decimal power = (decimal)(Math.Pow(10.0, (double)decimalPlaces));

    return Math.Truncate((power * numberToTruncate)) / power;
}

If your purpose in truncating the digits is for display reasons, then you just just use an appropriate formatting when you convert the double to a string.

Methods like String.Format() and Console.WriteLine() (and others) allow you to limit the number of digits of precision a value is formatted with.

Attempting to "truncate" floating point numbers is ill advised - floating point numbers don't have a precise decimal representation in many cases. Applying an approach like scaling the number up, truncating it, and then scaling it down could easily change the value to something quite different from what you'd expected for the "truncated" value.

If you need precise decimal representations of a number you should be using decimal rather than double or float.


I can't think of a reason to explicitly lose precision outside of display purposes. In that case, simply use string formatting.

double example = 12.34567;

Console.Out.WriteLine(example.ToString("#.000"));