c++以浮点形式输入并转换为字符串

c++ taking input in float and converting into string

本文关键字:转换 字符串 输入 c++      更新时间:2023-10-16

我想从只有两个小数点(999.99)的用户那里获得浮点输入,并将其转换为字符串

float amount;
cout << "Please enter the amount:";
cin.ignore();
cin >> amount;
string Price = std::to_string(amount);

我对该代码的输出是999.989990

to_string不允许您指定要格式化的小数位数。I/O流do:

#include <sstream>
#include <iomanip>
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << amount;
std::string Price = ss.str();

如果需要精确地表示十进制值,则不能使用二进制float类型。也许你可以乘以100,将价格表示为一个精确的整数便士。

如果您想将数字四舍五入到两位小数,可以尝试:

amount = roundf(amount * 100) / 100;

然后将其转换为std::string