If some numbers are given during Qt programming, after rounding them up, keep two decimal places

Numbers of type double are rounded to two decimal places

Scenes

During the development process, some double-type numbers need to be displayed, but they cannot be displayed directly, and two decimal places need to be rounded up. like:

0.124567 rounded to two decimals 0.12
0.231234 rounded to two decimals 0.23
12.3416 rounded to two decimals 12.34
34.2578 rounded to two decimals 34.26

Method to realize

There are two ways to implement the above problem. Record one by one below.

method one

In addition to rounding a number to two decimal places, this method can also convert a number to a value required by a percentage while rounding to two decimal places.
like:

0.123456 Rounded to 2 decimals, 0.12
2.1367 Rounded to 2 decimals, 2.14
0.125634 Converted to percentage, rounded to 2 decimals 12.56
0.125684 Converted to percentage, rounded to 2 decimals 12.57

Here is the implementation:

double makeValueKeepTwoDecimal(
    const double &dValue, const int &nType)
{
    
    
    double dTransValue = 0.00;
    int nTempValue = 0;
    int nValue = 0;
    if (nType == 1)  // %
    {
    
    
        nTempValue = dValue * 100000;
        nValue = dValue * 10000;
    }
    else if (nType == 2)  // not %
    {
    
    
        nTempValue = dValue * 1000;
        nValue = dValue * 100;
    }

    int nLastPersonValue = nTempValue % 10;
    nLastPersonValue >= 5 ? ++nValue : nValue;
    dTransValue = nValue / 100.00;
    return dTransValue;
}

Method Two

Use qt's own function QString::number to achieve, the following is the implementation:

QString stage(double v, int precision) //precision为需要保留的精度,2位小数变为2
{
    
    
    return (v >= 0.00 ? QString::number(v, 'f', precision) : "");
}

Method 2 is applied as follows:

QString strNum = stage(1.2345456,2); // "1.23"
QString strPerNum = stage(0.231456*100,2); //"23.15"

Summarize

Of the above two methods, method 2 is better to use, and method 2 can be used first. Because in method 1, if the value is 100 after rounding to two decimal places, only 100 will be displayed, and 100.00 will not be displayed. Method 2 does not have such a problem.

Guess you like

Origin blog.csdn.net/blqzj214817/article/details/130620049