Important: Please read the Qt Code of Conduct -

Decimal type that integrates well with Qt

  • Hello,
    Does anybody have a recommendation for a library that provides a decimal type which will allow for accurate base 10 arithmetic operations? I am looking for a solution that will integrate well with QDebug, QtSql, etc. This is for Qt c++.


  • First, are you sure you need a fixed precision decimal type (assuming that's what you really mean), and what are your limit requirements?

  • @Kent-Dorfman When using doubles and float I am getting rounding errors. The calculations involve multiple steps of multiplying, adding, etc. The rounding errors seem to accumulate. I just need reliable 4 decimal places with the ability to limit to 2 decimal places.

    How can I reliably round doubles and floats to say 2 decimal places? This is not for printing, this is for numbers that will be used in calculations. I have seen the approaches that convert to ints. I will give this approach a try. Found this example in another thread:

    round(88.33500 * 100) / 100; // print 88.34

  • @JohnGa
    You cannot reliably do floating point arithmetic, accurate to any number of places. Floating point numbers only have approximate representations, and can only represent discrete real values. You should always use double in preference to float.

    For a fixed number of dps like 2 or 4 you can indeed do your arithmetic by multiplying up and dealing with int/long, so long as that does not exceed integer range. I haven't checked, but a C++ library like boost probably offers fixed-dp arithmetic. Qt/C++ does not offer a type to interact with SQL DECIMAL types, unfortunately, you have to roll that yourself if you want to use it.

Log in to reply