Results 1 to 2 of 2

Thread: Extract int and decimal points from a float

  1. #1
    Join Date
    Feb 2014
    Posts
    1
    Platforms
    Windows

    Default Extract int and decimal points from a float

    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

  2. #2
    Join Date
    Sep 2009
    Location
    Wroclaw, Poland
    Posts
    1,394
    Thanked 342 Times in 324 Posts
    Qt products
    Qt4 Qt5
    Platforms
    MacOS X Unix/X11 Windows Android

    Default Re: Extract int and decimal points from a float

    One solution is to convert the value to string and split it by '.' (dot) character:
    Qt Code:
    1. const float value = 3.141592;
    2. const int precision = 6;
    3. const QString string = QString::number(value,'g',precision);
    4. const QStringList splitted = string.split('.');
    5. qDebug() << splitted;
    6. // should output ("3","141592"), you can then convert them to integer values with QString::toInt method
    To copy to clipboard, switch view to plain text mode 
    .
    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 :
    Qt Code:
    1. const float value = 3.141592;
    2. const int x = floor(value);
    3. const float y = value-x;
    4. // x == 3;
    5. // y ~= 0.141592
    To copy to clipboard, switch view to plain text mode 

Similar Threads

  1. Replies: 2
    Last Post: 2nd May 2012, 09:49
  2. Replies: 4
    Last Post: 18th May 2011, 17:59
  3. To underline the numbers behind the decimal points?
    By wookoon in forum Qt Programming
    Replies: 3
    Last Post: 14th December 2010, 23:01
  4. Rounding a float to X decimal places
    By qlands in forum General Programming
    Replies: 2
    Last Post: 22nd June 2010, 21:02
  5. Replies: 1
    Last Post: 10th February 2009, 09:42

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.