广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C++float转std::string小数位数控制问题
  • 913
分享到

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

C++floatC++std::stringfloat转std::stringC++小数位数控制 2022-11-13 19:11:53 913人浏览 薄情痞子
摘要

目录float转std::string 小数位数控制std::stringstream 方式sprintf 方式string转float显示位数有误;cout 的 precision

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

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

--结束END--

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

本文链接: https://www.lsjlt.com/news/170991.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作