繁体   English   中英

Qt/C++:如何将浮点数四舍五入到最接近的正数,最多保留 2 位小数

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

我正在做一些单位转换。 所以得到的转换之一是 0.0024,但我想用 2 个十进制格式表示它,如 0.01。

因此,当我尝试使用 qround 和 Qstring::number() 函数时,它返回 0。

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

这里xy0

所以我的问题是如何将其四舍五入到最接近的正数 0.01

由于您有修剪数字的特殊需求,因此您可以滚动自己的函数。

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

输出:

0.01
100
100.22
100.23
0.01

您想要的是将值向上舍入,也称为结果的“上限”。 如果值 < .5,则“四舍五入”一个数字将始终向下舍入,否则向上舍入。 您还需要一些基本的数学运算来指定要四舍五入的小数位数。

#include <QtMath>

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

或不带 Qt:

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

100.00.01对应于您希望得到的小数位数。 对于一位小数,它将是10.0 / 0.1 ,或者对于三个1000.0 / .001 ,依此类推。

您也可以在最后一步中除以乘以相同的数量。 不过,浮点乘法通常要快得多,以防万一。

ceil(0.0024 * 100.0) / 100.0;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM