Thread: Problem with rounding floating points

  1. #1
    Registered User MacNilly's Avatar
    Join Date
    Oct 2005
    Location
    CA, USA
    Posts
    466

    Problem with rounding floating points

    Code:
    int convMinutes(double x)
    {
        int mins = static_cast<int>(x) * 60;
        cout << x - static_cast<int>(x);
        mins = (x - static_cast<int>(x)) * 100;
        cout << mins;
        
        return mins;
    }
    The problem is to take a floating point number (x) and look at it as if it's a time input in format HH.MM. If I enter, say 12.59 as x, the first cout outputs .59. The second one outputs 58. .59 * 100 is not 58. I can only assume some internal rounding is messing up my conversion.

    Any insights, ideas, would be much appreciated.
    Last edited by MacNilly; 02-17-2006 at 02:13 AM.

  2. #2
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You could add half a percent to round it:
    mins = (x - static_cast<int>(floor(x)) + 0.005) * 100;

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    .59 * 100 is not 58.
    No, but .589999999999999999 cast to an int and THEN multiplied by 100 is 58. Everything stored on a computer is stored in binary--that's the only thing computers know how to do--and there is no exact conversion from decimal to binary for some numbers.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >No, but .589999999999999999 cast to an int and THEN multiplied by 100 is 58.
    Actually it's more like 0.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-06-2009, 07:45 AM
  2. Problem aligning floating point numbers
    By esbo in forum C Programming
    Replies: 4
    Last Post: 01-05-2009, 08:09 PM
  3. Replies: 8
    Last Post: 11-03-2008, 09:48 PM
  4. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM
  5. Problem with calculations
    By 3901LV in forum C Programming
    Replies: 2
    Last Post: 03-03-2005, 02:07 PM