-
decimal formatting
I have this function --
Code:
double Item::getPrice() {
return (price + (price * 0.07)).digits(2);
}
First of all, is digits(int) the correct way to format decimals (I only want two digits to the right of the decimal)? The compiler says I need a struct/class/union to the left of digits(). I'm not sure what I would use for that..
-
No. Did someone suggest you do it this way?
Also, the computer doesnt care how many decimal places there are, either should you. However, you only really need to worry about this sort of thing when you are doing output, ex "cout" to the screen. So this function should just return the result, then whatever function is responsible for the output should worry about how it should be printed. Check this link out, which has examples at the bottom: setprecision - C++ Reference
-
Code:
Beverage coke("coke", 3.65, false);
cout<<setprecision(3)<<coke.toString();
No matter what I change the setprecision parameter to, it always displays 3.9055. Is it because I am calling a function? toString() looks like this.
Code:
string Beverage::toString() {
ostringstream result;
if(isAlcoholic == true)
result<<getName()<<" is an alcoholic beverage."<<std::endl;
else
result<<getName()<<" is an non-alcoholic beverage."<<std::endl;
result<<"It's price is "<<getPrice()<<"."<<std::endl;
return result.str();
}
-
You should use setprecision within the toString() member function. By the way, have you considered overloading operator<< for std::ostream instead of writing a toString() member function?
-
Okay I got that. If I wanted it in "##.##" form, what can I use to do that? Does precision handle that? Or is there some other way to do it?
-
You could use std::setw with std::setfill. Frankly though, this kind of formatting is not one of the strong points of C++'s output streams; C's formatted output functionality probably does this better. You can get similiar printf-like functionality for C++ output streams via Boost.Format.