简体   繁体   中英

Qt/C++: How to roundup floating number to nearest positive number with upto 2 decimal place

I am working on some unit conversion. So one of the resultant conversion is 0.0024 but I want to represent this in 2 decimal format like 0.01.

So when I am trying with qround and Qstring::number() function its returning 0.

double x = Qstring::number(0.0024, 'f', 2); double y = qround(0.0024);

here x and y is 0

So my question is how to round it to nearest positive number 0.01

Since you have your special need for trimming a number, you can roll your own function.

#include <iostream>

namespace MyApp
{
   double trim(double in)
   {
      int v1 = static_cast<int>(in);             // The whole number part.
      int v2 = static_cast<int>((in - v1)*100);  // First two digits of the fractional part.
      double v3 = (in - v1)*100 - v2;            // Is there more after the first two digits?
      if ( v3 > 0 )
      {
         ++v2;
      }

      return (v1 + 0.01*v2);
   }
}

int main()
{
   std::cout << MyApp::trim(0.0024) << std::endl;
   std::cout << MyApp::trim(100) << std::endl;
   std::cout << MyApp::trim(100.220) << std::endl;
   std::cout << MyApp::trim(100.228) << std::endl;
   std::cout << MyApp::trim(0.0004) << std::endl;
}

Output:

0.01
100
100.22
100.23
0.01

What you want is to round the value up , otherwise known as the "ceiling" of the result. Just "rounding" a number will always round down if value is < .5 and up otherwise. You also need some basic math to specify the number of decimal places to round to.

#include <QtMath>

double y = qCeil(0.0024 * 100.0) * 0.01;  // y = 0.01

Or w/out Qt:

#include <cmath>
using std::ceil;
double y = ceil(0.0024 * 100.0) * 0.01;  // y = 0.01

The 100.0 and 0.01 correspond to the number of decimal places you wish to end up with. For one decimal it would be 10.0 / 0.1 , or for three 1000.0 / .001 , and so on.

You could also just divide in the last step by the same amount you multiplied by. Floating point multiplication is typically much faster though, in case it matters.

ceil(0.0024 * 100.0) / 100.0;

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