简体   繁体   中英

How to stop the number from rounding up when using setprecision?

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

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;
}

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.

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