C++ float转std::string 小数位数控制问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++ float转std::string 小数位数控制问题

Atticus_DY   2022-11-09 我要评论

float转std::string 小数位数控制

std::stringstream 方式

    float a = 1122.334455;
    std::stringstream buf;
    buf.precision(2);//覆盖默认精度
    buf.setf(std::ios::fixed);//保留小数位
    buf << a << "文字";
    std::string str;
    str = buf.str();

sprintf 方式

    float a = 1122.334455;
    char* chCode;
    chCode = new(std::nothrow)char[20];
    sprintf(chCode, "%.2lf", a);// .2 是控制输出精度bai的,两位小数
    std::string strCode(chCode);
    delete []chCode;

string转float显示位数有误;cout 的 precision 成员函数

问题描述

在进行string转float过程中,发现有些数显示位数不同(存在数精度少了一位的情况,例如:0.1285354 转换后,显示 0.128535)

数据如下:

0.0281864
-0.0635702
0.0457153
0.1285354
-0.0254498
...

问题分析

后了解到 float 只显示有效位数 6 位, 而 double 显示有效位数 15 位

  • float有效数字位为6 – 7位,字节数为4,指数长度为8位,小数长度为23位。取值范围为 3.4E-38~3.4E+38。
  • double有效数字位为15 – 16位,字节数为8,指数长度为11位,小数长度为52位。取值范围为1.7E-308~1.7E+308。

随即思考,是不是转换后赋值到了float上,导致精度降低呢?

马上修改赋值到double类型上,然而任然显示有误。

这才想到会不会使 cout 输出精度的问题,搜索后发现 cout 需要调用 precision() 成员函数来设置显示精度,而 cout 默认精度为6位有效数字,哈哈真是凑巧,跟 float 精度一样。

修改后代码如下:

#include <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main(int argc, char *argv[]) {
    const string tmp_str = "0.1285354";
    float tmp_f = 0;
    double tmp = 0;
    cout.precision(16);
    cout << sizeof(tmp_f) << "--" << sizeof(tmp) << endl;
    cout << stof(tmp_str) << endl;
    cout << stod(tmp_str) << endl;
    cout << stold(tmp_str) << endl;
    cout << strtod(tmp_str.c_str(), NULL) << endl;
    cout << atof(tmp_str.c_str()) << endl;
    tmp = 0.1234567890123456;
    cout << tmp << endl;
    return 0;
}

程序输出

nvidia@nx:~/pengjing/cuda$ ./location 
4--8
0.1285354048013687
0.1285354
0.1285354
0.1285354
0.1285354
0.1234567890123456

cout 设置浮点数输出精度方法

方法一(全局设置 cout 输出精度)

#include <iostream>
double tmp = 0.1234567890123456;
cout.precision(16);    //此处设置后,全局有效;cout浮点数输出精度均为16
cout << tmp << endl;

方法二(全局设置 cout 输出精度)

#include <iostream>
#include <iomanip>
double tmp = 0.1234567890123456;
cout << setprecision(16) << tmp << endl; //此处设置后,全局有效;后面cout浮点数输出精度均为16
cout << 0.1234567890123456 << endl;    // 0.1234567890123456

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们