簡體   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