-1

I have a decimal variable with following values

a = 99.9999
b = 88.423766
c = 11.896589

Here I am trying to convert with 4 decimal points.

And I used

a = Math.Round(Convert.ToDecimal(a), 4);
b = Math.Round(Convert.ToDecimal(b), 4);
c = Math.Round(Convert.ToDecimal(c), 4);

However I get values like

a = 100
b = 88.4238
c = 11.8966

Though the preferred values are with out rounding,

a = 99.9999
b = 88.4237
c = 11.8965

How can I achieve it.

TBA
  • 1,077
  • 5
  • 41
  • 80
  • 1
    http://stackoverflow.com/questions/6872165/rounding-to-at-least-2-to-4-decimal-places – marsh Nov 10 '14 at 15:44
  • 1
    @marsh That question wants rounding, this one wants truncation. – juharr Nov 10 '14 at 15:46
  • 2
    There is no overload for `Convert.ToDecimal` that has two parameters of which the second one is an `int` -- you probably meant `Convert.ToDecimal(Math.Round(...))` Could you correct your question so the code is actually what you're using? – Jeroen Mostert Nov 10 '14 at 15:53

2 Answers2

3

There's no built-in function to truncate a decimal to N decimal places, but it is very straightforward:

a = Math.Truncate(a * 10000m) / 10000m;

or as a helper function:

public decimal Truncate(decimal d, int n)
{
    // calculate 10^n
    decimal t = (decimal)Math.Pow(10.0,n);

    return Math.Truncate(d * t) / t;
}

or as an extension method:

public decimal Truncate(this decimal d, int n)
{
    // calculate 10^n
    decimal t = (decimal)Math.Pow(10.0,n);

    return Math.Truncate(d * t) / t;
}

Note that the difference between Math.Truncate and Math.Floor is the handling of negative numbers. Math.Truncate literally truncates the decimal digits, while Math.Floor returns the highest integer less than the input, so Math.Truncate(-1.2) will return -1 while Math.Floor(-1.2) will return -2.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

This will keep 4 decimals and truncate the rest:

a = decimal.Truncate(a*10000)/10000;
b = decimal.Truncate(b*10000)/10000;
c = decimal.Truncate(c*10000)/10000;
Richnau
  • 387
  • 1
  • 15