[英]c++ taking input in float and converting into string
我想只用兩個小數點(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流可以:
#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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.