在Java中處理浮點值時,調用toString()方法會給出一個列印值,該值具有正确的浮點數有效數字.但是,在C中,通過stringstream列印float會在5位或更少位數後對值進行舍入.有沒有辦法将C中的浮點“漂亮地列印”到(假定的)正确數字的有效數字?
編輯:我想我被誤解了.我希望輸出是動态長度,而不是固定的精度.我熟悉setprecision.如果你檢視Double的java源代碼,它會以某種方式計算有效數字的數量,我真的想了解它是如何工作的和/或在C中輕松複制它的可行性.
public FloatingDecimal( double d )
{
long dBits = Double.doubleToLongBits( d );
long fractBits;
int binExp;
int nSignificantBits;
// discover and delete sign
if ( (dBits&signMask) != 0 ){
isNegative = true;
dBits ^= signMask;
} else {
isNegative = false;
}
// Begin to unpack
// Discover obvious special cases of NaN and Infinity.
binExp = (int)( (dBits&expMask) >> expShift );
fractBits = dBits&fractMask;
if ( binExp == (int)(expMask>>expShift) ) {
isExceptional = true;
if ( fractBits == 0L ){
digits = infinity;
} else {
digits = notANumber;
isNegative = false; // NaN has no sign!
}
nDigits = digits.length;
return;
}
isExceptional = false;
// Finish unpacking
// Normalize denormalized numbers.
// Insert assumed high-order bit for normalized numbers.
// Subtract exponent bias.
if ( binExp == 0 ){
if ( fractBits == 0L ){
// not a denorm, just a 0!
decExponent = 0;
digits = zero;
nDigits = 1;
return;
}
while ( (fractBits&fractHOB) == 0L ){
fractBits <<= 1;
binExp -= 1;
}
nSignificantBits = expShift + binExp +1; // recall binExp is - shift count.
binExp += 1;
} else {
fractBits |= fractHOB;
nSignificantBits = expShift+1;
}
binExp -= expBias;
// call the routine that actually does all the hard work.
dtoa( binExp, fractBits, nSignificantBits );
}
在此函數之後,它調用dtoa(binExp,fractBits,nSignificantBits);處理一堆案例 – 這是來自OpenJDK6
為了更清晰,一個例子:
Java的:
double test1 = 1.2593;
double test2 = 0.004963;
double test3 = 1.55558742563;
System.out.println(test1);
System.out.println(test2);
System.out.println(test3);
輸出:
1.2593
0.004963
1.55558742563
C :
std::cout << test1 << "
";
std::cout << test2 << "
";
std::cout << test3 << "
";
輸出:
1.2593
0.004963
1.55559