Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QString:number with maximum 2 decimal places without trailing zero

Tags:

I have a division like this:

number / 1000.0 

Sometimes it gives answers like 96.0000000001, sometimes the division works as expected.

I want to limit my number to a maximum of two decimal places and without trailing zeros.

If it's 96.5500000001 it should show 96.55.

If it's 96.4000000001 it should show 96.4

It is possible to format a string in this way?

I've checked the documentation and it provides 'f' argument for specifying the number of the decimal places but this way the trailing zeros remain. This is what I have tried:

QString::number(number / 1000.0, 'f', 2) 

But this gives me for 96.4000000001 --> 96.40 instead of 96.4

Any solution? How can I format in this way?

like image 808
Neaţu Ovidiu Gabriel Avatar asked Jul 22 '14 08:07

Neaţu Ovidiu Gabriel


People also ask

How do you limit two decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do you write a float value up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

What are trailing decimal places?

In mathematics, trailing zeros are a sequence of 0 in the decimal representation (or more generally, in any positional representation) of a number, after which no other digits follow.

How do you round to 2 decimal places in C++?

We can use the printf() and fprintf() function to round numbers to 2 decimal places by providing the %. 2f format specifier.


1 Answers

The documentation is pretty clear about what you should do:

A precision is also specified with the argument format. For the 'e', 'E', and 'f' formats, the precision represents the number of digits after the decimal point. For the 'g' and 'G' formats, the precision represents the maximum number of significant digits (trailing zeroes are omitted).

Therefore, use either the 'g' or 'G' format.

main.cpp

#include <QString> #include <QDebug>  int main() {     qDebug() << QString::number(96400.0000001 / 1000.0, 'g', 5);     qDebug() << QString::number(96550.0000001 / 1000.0, 'G', 5);     return 0; } 

main.pro

TEMPLATE = app TARGET = main QT = core SOURCES += main.cpp 

Build and Run

qmake && make && ./main 

Output

"96.4" "96.55" 
like image 171
lpapp Avatar answered Sep 17 '22 06:09

lpapp