PDA

View Full Version : Extract int and decimal points from a float



djm2
1st February 2014, 12:04
Hi there

I am working with QT creator 2.8.0 and I am trying to split up a value to be processed. I have a floating point value say for example 12.34567 and I want to extract the 12 part and the 34567 part separately. I will then use the two values in the rest of my code. Can anyone point me in the right direction? I saw this post - http://qt-project.org/forums/viewthread/12441 but it doesn't seem to like it. I know its an easy question but I am a newbie.

Thanks

stampede
1st February 2014, 16:08
One solution is to convert the value to string and split it by '.' (dot) character:


const float value = 3.141592;
const int precision = 6;
const QString string = QString::number(value,'g',precision);
const QStringList splitted = string.split('.');
qDebug() << splitted;
// should output ("3","141592"), you can then convert them to integer values with QString::toInt method

.
Another way is to operate on the float value itself, in order to extract the largest integer not greater than given value - a definition of the "floor" function :


const float value = 3.141592;
const int x = floor(value);
const float y = value-x;
// x == 3;
// y ~= 0.141592