如何在C++中保留小数位数?

5

我需要帮助将浮点数值四舍五入到小数点后一位。

我知道可以使用setprecision(x)cout << precision(x)来四舍五入整个浮点数,但我只想将小数部分四舍五入到十分位。


可能是Rounding to the second decimal spot的重复问题。 - jogojapan
3个回答

10

这里有另一种解决方案,不需要将其转换为整数:

#include <cmath>

y = floor(x * 10d) / 10d

8
#include <cmath>

int main() {
    float f1 = 3.14159f;
    float f2 = 3.49321f;
    std::cout << std::floor(f1 * 10 + 0.5) / 10 << std::endl; 
    std::cout << std::floor(f2 * 10 + 0.5) / 10 << std::endl;
    std::cout << std::round(f1 * 10) / 10 << std::endl; // C++11
    std::cout << std::round(f2 * 10) / 10 << std::endl; // C++11
}

0
你可以这样做:
int main()
{

    float a = 4212.12345f;
    float b = a * 10.0f;
    float c = ((int)b) / 10.0f;

    cout << c << endl;
    return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接