首页 > 解决方案 > Qt/C++:如何将浮点数舍入到最接近的正数,最多保留 2 位小数

问题描述

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

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

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

这里是x_y0

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

标签: c++qt

解决方案


由于您有修剪数字的特殊需要,您可以滚动自己的功能。

#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

推荐阅读