Reputation: 13
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
Upvotes: 0
Views: 68
Reputation: 254461
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.
Upvotes: 4
Reputation: 10385
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
.
Upvotes: 0