Thread: float to absolute value

  1. #1

    Unhappy float to absolute value

    Hi there
    I want to convert a float to its absolute value and I have discovered the fabs() function but it only works if I set my variable to a double. I really want my variable to remain a float, is there a way to do this?

  2. #2
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    fabs() will work with floats, they'll just be promoted within the function.

    If you want to keep using floats (for whatever reason) then just make sure that the variable you are returning into is a float. Your compiler may warn you about possible loss of data but you can either ignore these warnings or cast the function to a float -

    float y = (float)fabs(x);

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    if ( x < 0.0 ) x = -x;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4


    Thanks Zen and Salem!
    Excellent help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-13-2009, 03:25 PM
  2. Replies: 14
    Last Post: 06-28-2006, 01:58 AM
  3. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 02:19 AM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM