在 Java 中处理浮点值时,调用该toString()
方法会给出一个打印值,该值具有正确数量的浮点有效数字。但是,在 C++ 中,通过打印浮点数stringstream
将在 5 位或更少位后舍入该值。有没有办法将 C++ 中的浮点数“漂亮地打印”到(假设的)正确数量的有效数字?
编辑:我想我被误解了。我希望输出具有动态长度,而不是固定精度。我熟悉setprecision。如果您查看 Double 的 java 源代码,它会以某种方式计算有效位数,我真的很想了解它是如何工作的和/或在 C++ 中轻松复制它的可行性。
/*
* FIRST IMPORTANT CONSTRUCTOR: DOUBLE
*/
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 << "\n";
std::cout << test2 << "\n";
std::cout << test3 << "\n";
输出:
1.2593
0.004963
1.55559