[solved] Addition of Float does not give precise result
-
Hi,
I am doing addition of prices in my application. I have values as QStrings 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?
-
Hi,
float is a 32bit data type with 8 precision digits; you need more precision so you must use double (16 precision digits) or long double (24 precision digits).
PS: long double precision depends on the platform
-
-
Thanks all,
using double solved the issue
-
[quote author="Abin" date="1403934198"]Thanks all,
using double solved the issue[/quote]
Not quite. The issue is still there, hiding from you. As your numbers cannot be represented exactly as base-2 floating point numbers, you will always have rounding errors, and eventually that may still affect your computation. The correct solution is to use integer arithmetic on cents.