Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal type in Qt (C++)

Tags:

c++

decimal

qt

What is the correct type to use in Qt development (or C++ in general) for decimal arithmetic, i.e. the equivalent of System.Decimal struct in .Net?

  • Does Qt provide a built-in struct? (I can't find it in the docs, but maybe don't know where to look.)
  • Is there a "standard" C++ library to use?
like image 314
Dave Mateer Avatar asked Mar 30 '10 18:03

Dave Mateer


2 Answers

What is the correct type to use in Qt development (or C++ in general) for decimal arithmetic, i.e. the equivalent of System.Decimal struct in .Net?

Neither C++ standard library nor Qt has any data type equivalent to System.Decimal in .NET.

Does Qt provide a built-in struct? (I can't find it in the docs, but maybe don't know where to look.)

No.

Is there a "standard" C++ library to use?

No.

But you might want to have a look at the GNU Multiple Precision Arithmetic Library.

[EDIT:] A better choice than the above library might be qdecimal. It wraps an IEEE-compliant decimal float, which is very similar (but not exactly the same as) the .NET decimal, as well utilizing Qt idioms and practices.

like image 167
missingfaktor Avatar answered Sep 27 '22 22:09

missingfaktor


There is no decimal type in C++, and to my knowledge, there is none provided by Qt either. Depending on your range of values, a decent solution may be to just use an unsigned int and divide/multiply by a power of ten when displaying it.

For example, if we are talking about dollars, you could do this:

unsigned int d = 100; // 1 dollar, basically d holds cents here...

or if you want 3 decimal places and wanted to store 123.456

unsigned int x = 123456; and just do some simply math when displaying:

printf("%u.%u\n", x / 1000, x % 1000);

like image 20
Evan Teran Avatar answered Sep 27 '22 22:09

Evan Teran