How to truncate decimal to X decimal places? [closed]

1

I'm using the following code, but when I send ex: '10 .100 'to 2 houses it returns '10 .1', but should be '10 .10 '

    public decimal TruncarDecimal(decimal value, int decimalPlaces)
    {
        decimal integralValue = Math.Truncate(value);

        decimal fraction = value - integralValue;

        decimal factor = (decimal)Math.Pow(10, decimalPlaces);

        decimal truncatedFraction = Math.Truncate(fraction * factor) / factor;

        decimal result = integralValue + truncatedFraction;

        return result;
    }
    
asked by anonymous 19.09.2017 / 16:58

2 answers

3

Give support, view the documentation . There you have no decimal places parameter, with this information and even as it should be the criterion of the rounding.

Math.Round(valorDecimal, 2);

If what you want is not rounding up then do Truncate() climbing:

Math.Truncate(100 * valorDecimal) / 100;

But this is basically what's in the question.

    
19.09.2017 / 17:02
1

Try using

Math.Truncate

For example:

using System;

class Program
{
    static void Main()
    {
        decimal a = 1.223M;
        double b = 2.913;

        a = Math.Truncate(a);
        b = Math.Truncate(b);

        Console.WriteLine(a);
        Console.WriteLine(b);
    }
}

Outputs:

1
2

Now if you need to display the value with two decimal places use the code:

decimalVar.ToString("#.##");

More information about Math.Truncate see this link: #

    
19.09.2017 / 17:03