C # - Truncate after position

I have a double typed variable. This variable stores information that is part of a more complex formula. It's important to note that this variable can only include information up to the tenth location or one decimal place (i.e. 10.1, 100.2, etc.). However, when determining this value, it must be calculated in such a way that the entire past from the tenth place is truncated, rather than rounded. For example:

if the value is 10.44, the value of the variable should be 10.4. if the value is 10.45, the variable value must also be set to 10.4

How do I truncate values โ€‹โ€‹in C # relative to decimal place?

+2


source to share


5 answers


Using extension method:

public static double RoundDown(this double value, int digits)
{
     int factor = Math.Pow(10,digits);

     return Math.Truncate(value * factor) / factor;
}

      



Then you just use it like this:

double rounded = number.RoundDown(2);

      

+6


source


System.Math.Truncate (d * 10) / 10



0


source


You have to do it yourself:

    public static decimal Truncate(decimal value, int decimals)
    {
        if ((decimals < 0) || (decimals > 28))
        {
            throw new ArgumentOutOfRangeException("decimals", "The number of fractional decimals must be between 0 and 28.");
        }

        decimal integral = Math.Truncate(value);
        decimal fractional = value - integral;
        decimal shift = (decimal)Math.Pow(10, decimals);

        fractional = Math.Truncate(shift * fractional);
        fractional = fractional / shift;

        return (integral + fractional);
    }

      

0


source


While I will probably use Phillippe's answer, if you want to avoid scaling the number (not likely to be a problem for 1dp), you can:

    public static double RoundDown(this double x, int numPlaces)
    {
        double output = Math.Round(x, numPlaces, MidpointRounding.AwayFromZero);
        return (output > x ? output - Math.Pow(10, -numPlaces) : output);
    }

      

0


source


Generally, if you are working with numbers where the exact decimal representation is important, you should use decimal

- not double

.

With help, decimal

you can do something like ...

decimal d = ...;
d = decimal.Truncate(d*10)/10;

      

If you use a value double

, your truncated number will generally not be accurately represented - you may get extra digits or minor rounding errors. For example, Math.Truncate((4.1-4.0)*10)

not 1, but 0.

0


source







All Articles