Hello!

I implement the project on Qt. I am trying to deduce a fraction whose denominator is not a power of two (19 decimal places). For example, 1/5 = 0, 0000000000000000111.

It is clear that such a view is a feature of the representation of floating point numbers in C ++. But how to display the result available to the user (1/5 = 0.2)? The output format is desirable not to change.

I use the following method to display the number.

QString MainWindow::numberFormat(const double &number) { QString str = QLocale::system().toString(number, 'f', 21); return str.remove(QRegExp(",?0+$")); } 

I ask for your help, thank you in advance.

    2 answers 2

    I once found only one convenient way out of this situation. You need to implement your own algorithm for dividing the numerator by the denominator "corner", as in school, displaying one decimal digit of the result after another. Having obtained the string of the required length from the digits after the comma, we delete the zeros at the end.

    The code of such a function is extremely simple (pseudocode, from the head):

     void div (unsigned int num, unsigned int denom, size_t n) { printf ("%u,", num/denom); // Целая часть num %= denom; // Дробная часть. while (n-- > 0) { // n - сколько нужно цифр. num *= 10; unsigned int d = num/denom; printf ("%u", d); num -= d*denom; } } 

    Of course, instead of printf you need something else, for example, storing numbers in a string or what you are going to do there, I do not know.

    • everything would be fine, but I can have double - Dexter Morgan
    • one
      Who prevents to multiply them by 10 until they become whole? On the other hand, if the question of accuracy arises somewhere, it means that you need to do everything from the very beginning in rational fractions, and not in double . Even if a person entered a type number 3,14 you can immediately turn it into 314/100 at the 314/100 . I do not see a problem at all. - Zealint

    Well, read the documentation - you're trying to print 21 characters ( toString(number, 'f', 21) ). What for? Remove output accuracy to real. I think there are 6 signs suggested by default, as they say, enough for the eyes ... And even less.

    • it is clear that 21 characters. I have a calculator, I need to display it in this format. - Dexter Morgan
    • 2
      In this case, take the library to calculate with an accuracy of 40 characters, and cut off 21. Do not find yourself only in this situation . - Harry