简体   繁体   English

输出除法结果,包括小数点后的数字-Qt

[英]Output division result including digits after decimal - Qt

I am sorry if it's already answered in here, but I couldn't find the exact solution I am looking for. 很抱歉,如果它已经在这里回答了,但是我找不到我想要的确切解决方案。

I am trying to output the result of a division of two variable which is continuously changing. 我试图输出两个变量的除法结果,该结果不断变化。 The result may vary from 0.00 to 100.12314235234523 (not exactly this specific, I just wanted to give you an idea). 结果可能从0.00到100.12314235234523(不完全是具体的,我只是想给您一个想法)。 I want to print the result only 2 digits after the decimal point, if there is nothing after decimal, it should print 2 zeroes after decimal. 我想仅在小数点后2位打印结果,如果小数点后没有任何内容,则应在小数点后打印2个零。

For example: 例如:

10 / 5 = 2.00 10/5 = 2.00

23 / 6 = 3.83 23/6 = 3.83

I don't need to round up the result for example, if the output is: 73.4869999, I don't need it to be 73.49, 73.48 is fine with me. 例如,如果输出为:73.4869999,我不需要四舍五入,我不需要是73.49,73.48就可以了。

What I have written so far is: 到目前为止,我写的是:

packet_loss[2]->setText(QString("%1%2%3").arg(((data.packet_loss_tx) * 100) / data.packets_tx).
                                          arg(locale.decimalPoint()).
                                          arg((((data.packet_loss_tx) * 100) % data.packets_tx), 2, 10, QChar('0')));

But this prints all the values after the decimal point. 但这会在小数点后打印所有值。 I can divide this part arg((((data.packet_loss_tx) * 100) % data.packets_tx) with 10, 100 or 1000 to reduce the number of decimals after the decimal point but this is a variable which changes every seconds. So if the output is 3 digits after decimal and I divide it by 10, I will get proper output, but the next value may be 5 digits after decimal and division by 10 will give me 4 digits after decimal. I want the final output to show only 2 digits after decimal. 我可以将这部分arg((((data.packet_loss_tx) * 100) % data.packets_tx) 10、100或1000,以减少小数点后的小数位数,但这是arg((((data.packet_loss_tx) * 100) % data.packets_tx)更改一次的变量。输出是十进制后的3位,然后除以10,我将得到正确的输出,但是下一个值可能是十进制后的5位,而除以10将得到十进制后的4位。我希望最终输出仅显示小数点后2位。

You could try to use QString::number() function with specific formatting options (two digits precision). 您可以尝试将QString::number()函数与特定的格式设置选项一起使用(两位数精度)。 For example: 例如:

auto s = QString::number(100.12914235234523, 'f', 2); // Gives "100.13"

Besides, if you use floating point numbers, it's better to multiply them with floating point numbers too. 此外,如果使用浮点数,最好也将它们与浮点数相乘。 Ie you need to perform your calculations using 100.0 instead of integer value 100. 即您需要使用100.0而不是整数值100进行计算。

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

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