简体   繁体   中英

c++ taking input in float and converting into string

I want to take float input from user with only two decimal point(999.99) and convert it into string

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

my output for this code is 999.989990

to_string doesn't let you specify how many decimal places to format. I/O streams do:

#include <sstream>
#include <iomanip>

std::stringstream ss;
ss << std::fixed << std::setprecision(2) << amount;
std::string Price = ss.str();

If you need to represent the decimal value exactly, then you can't use a binary float type. Perhaps you might multiply by 100, representing prices as an exact integer number of pennies.

If you want to round the number to two decimal digits, you could try:

amount = roundf(amount * 100) / 100;

And then convert it into std::string .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM