c++ - 输出 float 为三位数,或更多以避免指数

标签 c++ floating-point cout

我正在尝试将 float 输出为三位数,或者在必要时输出更多,以避免出现指数。

一些例子:

0.12 // 0.123 would be ok
1.23
12.3
123
1234
12345

我得到的最接近的是

std::cout << std::setprecision(3) << f << std::cout;

但这会打印类似的东西

21       // rather than 21.0
1.23e+03 // rather than 1234

std::setprecisionstd::fixed 结合意味着我总是得到相同数量的小数点后数字,这不是我想要的。

使用 std::setw,123.456 仍将打印为 123.456 而不是 123。

有什么建议吗?

最佳答案

据我所知,最简单的解决方法是滚动一个函数来捕获它。我把它放在一起,它似乎有效。我不确定您是否希望大数字只有 3 位有效数字,或者他们是否应该将所有 sig figs 保留在小数点左侧,但进行修改并不难:

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

关于c++ - 输出 float 为三位数,或更多以避免指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19119043/

相关文章:

c++ - weak_ptr 是否与 unique_ptr 一起工作?

objective-c - 将时间转换为 float

math - float 学有问题吗?

c++ - 可以存储在 float 中的最大连续整数的定义常量?

c++ - 自动 cout 冲洗

c++ - 写入 .BMP - 图像失真

c++ - 从使用 numpy.save(...) 保存的文件中将 numpy 数组加载到 C 中

c++ - 如何使用 "Matlab Data/Engine API for c++"在 C++ 中加载 .mat

C++:&(std::cout) 作为模板参数

c++ - 打印到 Windows 控制台度数 (°) 和立方体符号 (³)