I am doing addition of prices in my application. I have values as QString
s and I convert to float and add. When it reaches high value, result is not precise. I read like float or double should not be used for currency addition and use separate variable for integer part and fractional part. My code and log is below:
qDebug ("m_totalPrice: %f + %f =", m_totalPrice, item.price.toFloat());
m_totalPrice += item.price.toFloat();
qDebug ("m_totalPrice: %f", m_totalPrice);
ui->totalLabel->setText(QString::number(m_totalPrice, 'f', 2));
m_totalPrice
is float
and item.price
is QString
logs:
- m_totalPrice: 424659.500000 + 22350.500000 =
m_totalPrice: 447010.000000- m_totalPrice: 447010.000000 + 18.900000 =
m_totalPrice: 447028.906250- m_totalPrice: 447028.906250 + 125.900002 =
m_totalPrice: 447154.812500- m_totalPrice: 447154.812500 + 125.900002 =
m_totalPrice: 447280.718750- m_totalPrice: 447280.718750 + 11.500000 =
m_totalPrice: 447292.218750- m_totalPrice: 447292.218750 + 22.500000 =
m_totalPrice: 447314.718750
Error is from line 2. Can someone tell how to resolve this?
Edit : since my question is not complete
In line 2 it shows addition of 447010.000000 + 18.900000 = 447028.906250
My doubt is after addition it should be at least 447028.9000..