Math.Truncate在大多数情况下,这是否相同:
double x = 1034.45
var truncated = x - Math.Floor(Math.Abs(x));
Run Code Online (Sandbox Code Playgroud)
哪里truncated == 0.45?
更新中...
感谢输入人!这对我有用:
[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");
}
Run Code Online (Sandbox Code Playgroud)
这个也是:
[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");
}
Run Code Online (Sandbox Code Playgroud)
您truncated将无法获得负值的正确值x.
要使用Math.Floor像Truncate一样向零舍入,只需这样做;
static double Truncate(double d)
{
return d > 0 ? Math.Floor(d) : -Math.Floor(-d);
}
Run Code Online (Sandbox Code Playgroud)