在c++中格式化双精度值

Format double value in c++

本文关键字:双精度 格式化 c++      更新时间:2023-10-16

我有一个双精度值,我想限制它的精度,然后转换为字符串。

double dblValue = 50.0000018963;

我需要将其转换为50.0和字符串格式。

在c++中可以使用std::stringstream和precision属性:

#include <iostream>
#include <sstream>
#include <string>
int main() {
    double d = 50.0123456789;
    std::string s;
    std::stringstream sstream;
    sstream.setf(std::ios::fixed);
    sstream.precision(1);
    sstream << d;
    s = sstream.str();
    std::cout << d << std::endl;
    std::cout << s << std::endl;
    return 0;
}

注意,精度继承自std::ios_base,所以std::cout也有。如果您只想输出此值,可以将std::cout.precision()设置为1。

你也可以在http://www.cplusplus.com/reference/ios/ios_base/precision/和http://www.cplusplus.com/reference/sstream/stringstream/

看一下sprintf的文档

sprtintf(yourchararrayORstring, "%.2f", dblValue);

注意:这只会将具有2个精度点的双精度值写入string,而不会四舍五入或修改您的dblValue

或按照Cory的建议

步骤1:std::round步骤2:std::to_string步骤3:????第四步:盈利!