0

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

3
  • Just omit cin.ignore();, it's completely unclear, why you want it to use here. Also you note not all exact decimals can be represented by a float or double value. Commented Mar 6, 2015 at 17:29
  • Let's see how you output the number. Commented Mar 6, 2015 at 17:30
  • @PaulMcKenzie Probably something like std::cout << Price << std::endl; Commented Mar 6, 2015 at 17:31

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.