在c++中格式化双精度值
Format double value in c++
我有一个双精度值,我想限制它的精度,然后转换为字符串。
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:????第四步:盈利!
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C 字符串返回字符串的整数/双精度/长整型值
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何使双精度值的 C++ 和 C# 中的结果相同
- 使用浮点数和双精度数的非常小数字的数学
- 使用 Xcode 将双精度存储在数组C++中
- 在 C++ 中将双精度变量写入二进制文件
- 如何从字符串转换为双精度*
- 为什么我的数组双精度函数不起作用?
- 高精度双精度的 Sprintf 格式化问题
- 使用 sprintf 格式化负整数/双精度
- 在c++中格式化双精度值
- 格式化的双精度输出
- 以二进制格式格式化 2D 双精度矩阵以读取 IDL 的最基本方法是什么?