0
我試圖轉換雙帕斯卡真實,但是當我轉換0.23現實我得到0.23999999真正的我如何可以截斷所有9999至0000C#雙現實
public static byte[] Double2Real48(double d)
{
byte[] r48 = new byte[6];
byte[] da = BitConverter.GetBytes(d);
for (int i = 0; i < r48.Length; i++)
r48[i] = 0;
//Copy the negative flag
r48[5] |= (byte)(da[7] & 0x80);
//Get the expoent
byte b1 = (byte)(da[7] & 0x7f);
ushort n = (ushort)(b1 << 4);
byte b2 = (byte)(da[6] & 0xf0);
b2 >>= 4;
n |= b2;
if (n == 0)
return r48;
byte ex = (byte)(n - 1023);
r48[0] = (byte)(ex + 129);
//Copy the Mantissa
r48[5] |= (byte)((da[6] & 0x0f) << 3);//Get the last four bits
r48[5] |= (byte)((da[5] & 0xe0) >> 5);//Get the first three bits
r48[4] = (byte)((da[5] & 0x1f) << 3);//Get the last 5 bits
r48[4] |= (byte)((da[4] & 0xe0) >> 5);//Get the first three bits
r48[3] = (byte)((da[4] & 0x1f) << 3);//Get the last 5 bits
r48[3] |= (byte)((da[3] & 0xe0) >> 5);//Get the first three bits
r48[2] = (byte)((da[3] & 0x1f) << 3);//Get the last 5 bits
r48[2] |= (byte)((da[2] & 0xe0) >> 5);//Get the first three bits
r48[1] = (byte)((da[2] & 0x1f) << 3);//Get the last 5 bits
r48[1] |= (byte)((da[1] & 0xe0) >> 5);//Get the first three bits
return r48;
}
這是正常的舍入誤差並且是預期的。並非所有浮點數都可以用二進制精確表示。如果你想更精確的使用'decimal',但是這個問題**仍然會發生。 – ChrisF 2011-02-05 18:28:17
其實在這種情況下這可能不是問題 - 我剛剛重讀了你的問題,並注意到這些數字並不是我認爲的那些。 – ChrisF 2011-02-05 18:34:49