[C++]将float保留2位小数并转成std::string

#include <iostream>

#include <sstream>

#include <iomanip>

std::string float2string(float value) {

std::ostringstream streamObj;

// Set Fixed -Point Notation

streamObj << std::fixed;

// Set precision to 2 digits

streamObj << std::setprecision(2);

//Add double to stream

streamObj << value;

// Get string from output string stream

return streamObj.str();

}

int main() {

float value = 3.14159;

std::string valueAsString = float2string(value);

std::cout << valueAsString << std::endl; // Prints "3.14"

return 0;

}

相关推荐
1000世界小札34 分钟前
《大话数据结构》第9章精读:归并排序与快速排序完整 C++ 实现
数据结构·c++·算法
2601_956121973 小时前
背包基础篇(01、完全、分组、多重、混合)
c++·算法·动态规划
丰锋ff3 小时前
基于 Qt 的智能门禁系统(二)
开发语言·qt
fpcc3 小时前
跟我学C++中级篇——编译期的条件选择
开发语言·c++
SomeB1oody4 小时前
【RustyML入门】6.3. 并行归约
开发语言·后端·机器学习·rust·教程
兴通物联科技4 小时前
SMT PCB 微小 DataMatrix 码扫不动问题分析 兴通 XT8601B 600 万像素工业读码器落地实践
大数据·人工智能·单片机·嵌入式硬件·算法·计算机视觉
mqiqe5 小时前
AgentScope Java 2.0 协议集成全景解析:A2A、AG-UI、Agent Protocol 三大开放协议实战指南
java·开发语言·ui
lzhdim5 小时前
12、JavaScript常见的内存泄露问题 - JavaScript学习系列文章
开发语言·前端·javascript·学习·ecmascript
脉动数据行情5 小时前
Java 实现台股 TWSE/TPEx 行情采集(个股 + K 线)
java·开发语言·twse·tpex·台股