1

float is rounding the numbers and when it becomes a scientific note that small rounding is multiplied several times

I am creating a function in case you add a number before the decimal point that number is pushed to the left and the number increases by one place in this case if you enter 0.001 it will come to 0.01 the more numbers you add the 1 will advance to the next place the problem is that after adding many numbers the float starts to round the number when the number becomes a scientific notation this rounding becomes a great inaccuracy since the number is being multiplied by 10 to advance one place if you keep putting the number one at some point it generates the result 1111111.13

int str_size = ui->box_total_USD->text().size();
    float result = 0;
    std::string str_value = ui->box_total_USD->text().toStdString();
    double value = ui->box_total_USD->text().toDouble();
    int length_after_point = 0;

    for(int c = str_size; c > 0 ; c--){
        if(str_value[c] == '.'){
            break;
        }
        length_after_point++;
    }    
    qDebug() << "Float value: " << value;
    qDebug() << "String value: " << QString::fromStdString(str_value);

    if(ui->box_total_USD->cursorPosition() >= str_size -2 ){//if the cursor is after the "."
        if(length_after_point == 4){//if the length of the string increases it will multiply by 10 if it decreases it will multiply by 0.01
            result = value * 10;
        }
        else{
            result = value * 0.1;
        }
        qDebug() << "Result: " << result;
        ui->box_total_USD->setText(QString::number(result, 'f', 2));
    }
Uiquehonra
  • 11
  • 3
  • floating point numbers have a limited number of significant digits. Theres no way around that, its how the are supposed to work – 463035818_is_not_an_ai Jan 18 '23 at 12:40
  • 1
    the question would be more clear if you would include the output and expected output in the quesiton – 463035818_is_not_an_ai Jan 18 '23 at 12:41
  • 1
    Many floating-point numbers (such as 0.01 IIRC) don't have a finite binary representation. Then, you cannot computer-represent them without rounding errors. Rounding errors are usually small, but if you multiply such numbers, they may become large. To have better accuracy, you can represent numbers as rational, or use some multiprecision library (Boost provides both). – Daniel Langr Jan 18 '23 at 12:51
  • so it is not possible to do this function through calculations? – Uiquehonra Jan 18 '23 at 13:10

0 Answers0