Silverlight doesn't have Math.Truncate! ... will this equivalent work?

This works as an equivalent for Math.Truncate

most / all cases:

double x = 1034.45
var truncated = x - Math.Floor(Math.Abs(x));

      

where truncated == 0.45

?

Updating ...

Thanks for the input people! This works for me:

[TestMethod]
public void ShouldTruncateNumber()
{
    double x = -1034.068;
    double truncated = ((x < 0) ? -1 : 1) * Math.Floor(Math.Abs(x));

    Assert.AreEqual(Math.Truncate(x), truncated, "The expected truncated number is not here");
}

      

It is too:

[TestMethod]
public void ShouldGetMantissa()
{
    double x = -1034.068;
    double mantissaValue = ((x < 0) ? -1 : 1) *
        (Math.Abs(x) - Math.Floor(Math.Abs(x)));
    mantissaValue = Math.Round(mantissaValue, 2);

    Assert.AreEqual(-0.07, mantissaValue, "The expected mantissa decimal is not here");
}

      

+3


source to share


2 answers


I have no idea if this functionality was introduced in Silverlight 4 or if we just missed it, but Decimal

has a static method forTruncate



public double Truncate(double d)
{
    return Convert.ToDouble(Decimal.Truncate(Convert.ToDecimal(d)));
}

      

+2


source


Yours truncated

will not get the correct value for negative values x

.

To use Math.Floor to round to zero like Truncate does, just do



static double Truncate(double d)
{
    return d > 0 ? Math.Floor(d) : -Math.Floor(-d);
}

      

+8


source







All Articles