Reputation: 31
const double MIN_STD_POWER = 90.111;
const double MAX_STD_POWER = 99.999;
double m_size = 2;
void display() const
{
if (m_size == MAX_STD_POWER || m_size == MIN_STD_POWER)
{
cout << m_size << " liters - " << m_type << endl;
}
else
{
cout << std::fixed << std::setprecision(2) << m_size << " liters - " << m_type << endl;
}
}
So basically, I'm trying to print m_size
to two significant digits, but not the MAX_STD_POWER
because it keeps rounding off to 100.00
instead of 99.999
. Why doesn't the above work?
Example of the output I want:
4.10 - liters
2.10 - liters
2.10 - liters
2.10 - liters
Ship doesn't exceed power regulation of: 99.999
Example of the output I get:
4.10 - liters
2.10 - liters
2.10 - liters
2.10 - liters
Ship doesn't exceed power regulation of: 100.00
Upvotes: 1
Views: 1316
Reputation: 2866
Round it to three decimals, when you need three, and round it to two, when you need two (live demo).
void display() const
{
const int precision = (m_size == MAX_STD_POWER || m_size == MIN_STD_POWER) ? 3 : 2;
cout << std::fixed << std::setprecision(precision) << m_size << " liters - " << m_type << endl;
}
Upvotes: 1
Reputation: 264749
Floating point numbers are going to round (to the nearest) when printed.
Part of the problem is that these numbers:
90.111
99.999
May not be represented exactly in a floating point number. Its probably very close but not exact. When I print these out with lots of precision I get:
99.998999999999995
90.111000000000004
2 significant digits:
1e+02
90
3 significant digits:
100
90.1
5 significant digits:
99.999
90.111
Simplest way to "round down is truncating to an integer.
int printable = m_size * 100; // 100 2 significant digits.
std::cout << (printable / 100) << "." << (printable % 100) << "\n"
But you can use doubles with in this situation.
std::cout << std::setprecision(5) << m_size << "\n";
Simple rule of thumb: Only use floating point were you really need it (the range of value is continuous not discrete). If you are storing something with some level of precession (ie to the nearest thousandth) store in an integer but multiply by 1000 so you store the value exactly. You only need to convert when printing and then simply use divide to get the integer part and mod to get the fraction part.
Upvotes: 0