PDA

View Full Version : Problem with displaying float value



mirluk
26th June 2008, 13:45
Hi,
I'm trying to display float value on the screen (temperature, 27,2 °C for example) but I'm getting just integer value (27,0°C).

Part of temperatue.cpp:


void Temperature::setValue(int value)
{
this->value=value;
update();
}


void Temperature::paint(QPainter* painter)
{
...
float x = (((((value)-6400)*120)/25600)-40);
digitalValue = QString("%1").arg(x,0,'f',1);
painter->drawText(0,0, 40,20, Qt::AlignRight, digitalValue);
...
}

mcosta
26th June 2008, 14:24
The problem is here


float x = (((((value)-6400)*120)/25600)-40);

All factors are integers, then the result is an integere value converted to float. Try this


float x = (((((value)-6400)*120.0)/25600)-40);

or


float x = ((((static_cast<float>(value)-6400)*120)/25600)-40);

sebastian
26th June 2008, 14:48
Hi,

I think that "setValue()" should take float instead of int argument.
Otherwise value which you're passing will always be converted to int.

Btw. line:


float x = (((((value)-6400)*120)/25600)-40);

for "value"(s) such that:


fabs(value-6400) < 25600/120

will always give you -40. But maybe that's what you want...

mirluk
26th June 2008, 15:33
Ok, I solved it on my own way.

Now, the code looks:


void Temperatura::setValue(float value)
{
this->value=value;
update();
}


void Temperatura::paint(QPainter* painter)
{
...
float x = (float)(((value-6400)*120)/25600)-40.0;
digitalValue = QString("%1").arg(x,0,'f',1);
painter->drawText(0,0, 40,20, Qt::AlignRight, digitalValue);
...
}


Anyway, thanks mcosta and sebastian for answers.