使用精度 & 将浮点数转换为字符串指定的小数位数? [英] Convert float to string with precision & number of decimal digits specified?

查看:21
本文介绍了使用精度 & 将浮点数转换为字符串指定的小数位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C++ 中将浮点数转换为字符串,同时指定精度 &小数位数?

How do you convert a float to a string in C++ while specifying the precision & number of decimal digits?

例如:3.14159265359 ->3.14"

推荐答案

典型的方法是使用 stringstream:

#include <iomanip>
#include <sstream>

double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();

参见固定

使用固定浮点表示法

str 流的 floatfield 格式标志设置为 fixed.

Sets the floatfield format flag for the str stream to fixed.

floatfield 设置为 fixed 时,浮点值使用定点表示法写入:该值用与小数部分中的位数完全相同的数字表示由 precision 字段 (precision) 指定并且没有指数部分.

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

setprecision.

对于技术目的的转换,例如将数据存储在 XML 或 JSON 文件中,C++17 定义了 to_chars 系列函数.

For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.

假设一个兼容的编译器(我们在撰写本文时缺乏),可以考虑这样的事情:

Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:

#include <array>
#include <charconv>

double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
                               std::chars_format::fixed, 2);
if (ec == std::errc{}) {
    std::string s(buffer.data(), ptr);
    // ....
}
else {
    // error handling
}

这篇关于使用精度 &amp; 将浮点数转换为字符串指定的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆