使用Math.Floor的意外结果

Chr*_*sUK -1 c# math

我正在编写一个应用程序,我需要处理毫米和英寸.我写了一些简单的代码来缩放两个度量单位之间我也有一些代码来取一个十进制数并将其转换为分数.但是,当我使用Math.Floor从小数中分割整数时,我发现我并不总是得到返回的预期值.我附上了一些代码来证明这个问题.我希望最终的结果是6但我得到5.我很难理解为什么.有任何想法吗?

// This is a .Net 4.5 console application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            double ValA = 6;
            double ValB = 0;
            double ValC = 0;
            double ValD = 0;

            ValB = ValA * 25.4;

            ValC = ValB / 25.4; 

            ValD = Math.Floor(ValC);

            Console.WriteLine(ValA.ToString());
            Console.WriteLine(ValB.ToString());
            Console.WriteLine(ValC.ToString()); // This returns 6 as expected
            Console.WriteLine(ValD.ToString()); // But this returns 5.

            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jac*_*ack 6

双打不是十进制数的精确表示,它们用二进制基数表示.它们不会精确转换为十进制数,因此您无法保证5*2.52/2.52等于5.0.我建议使用C#type Decimal.

编辑

有关C#Decimal类型的更多信息,请参阅此问题