据我所知,解决这个问题的最简单方法是滚动一个函数来捕获它。我把它放在一起,它似乎工作。我不确定您是否希望大数字只有 3 个有效数字,或者它们是否应该将所有 sig 无花果保留在小数点左侧,但进行修改并不难:
void printDigits(float value, int numDigits = 3)
{
int log10ofValue = static_cast<int>(std::log10(std::abs(value)));
if(log10ofValue >= 0) //positive log means >= 1
{
++log10ofValue; //add 1 because we're culling to the left of the decimal now
//The difference between numDigits and the log10 will let us transition across the decimal
// in cases like 12.345 or 1.23456 but cap it at 0 for ones greater than 10 ^ numDigits
std::cout << std::setprecision(std::max(numDigits - log10ofValue, 0));
}
else
{
//We know log10ofValue is <= 0, so set the precision to numDigits + the abs of that value
std::cout << std::setprecision(numDigits + std::abs(log10ofValue));
}
//This is a floating point truncate -- multiply up into integer space, use floor, then divide back down
float truncated = std::floor(value * std::pow(10.0, numDigits - log10ofValue)) / std::pow(10.0, numDigits - log10ofValue);
std::cout << std::fixed << truncated << std::endl;
}
测试:
int main(void)
{
printDigits(0.0000000012345);
printDigits(12345);
printDigits(1.234);
printDigits(12.345678);
printDigits(0.00012345);
printDigits(123456789);
return 0;
}
输出:
0.00000000123
12300
1.23
12.3
0.000123
123000000