Thread: Triming a float number

  1. #1
    Registered User RocketMan's Avatar
    Join Date
    Dec 2007
    Posts
    28

    Triming a float number

    Hi all,

    Im currently working in a long float number e.g:

    float number = 4.32525676;

    When i start to do other maths to this number, it gets to long. Is there a way i can trim this to less decimal places e.g:

    4.325

    Look forward to your reply.

    RocketMan.

  2. #2
    Technical Lead QuantumPete's Avatar
    Join Date
    Aug 2007
    Location
    London, UK
    Posts
    894
    Yes, multiply by 10 to the power of number of decimal places required. Truncate all decimal places and divide by 10 to the power of number of dp.
    Voila

    QuantumPete
    "No-one else has reported this problem, you're either crazy or a liar" - Dogbert Technical Support
    "Have you tried turning it off and on again?" - The IT Crowd

  3. #3
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    There are a few ways, but perhaps the "easiest" is just move the decimal place -- then move it back.

    Code:
    #include <stdio.h>
    
    int main(void)
    {
       double number = 4.32525676;
    
       double other = number * 10;   // 43.25...
       other *= 10;                  // 432.52...
       other *= 10;                  // 4325.256...
    
       other = (float)((int)other);
       other /= 10 * 10 * 10;
       printf("original = &#37;f. Chopped = %f", number, other);
       return 0;
    }
    Not sure how happy I'd be using that (even though I just wrote it)-- of course you should chuck it in a function if you plan to use it.

    The alternative is, rounding or printing to a certain precision.

  4. #4
    Registered User RocketMan's Avatar
    Join Date
    Dec 2007
    Posts
    28
    Hi,

    Thanks for all your input.

    It works a treat.

    Cheers

    Tuurbo46

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Issue w/ Guess My Number Program
    By mkylman in forum C++ Programming
    Replies: 5
    Last Post: 08-23-2007, 01:31 AM
  2. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  3. help w/another program!!!
    By edshaft in forum C++ Programming
    Replies: 2
    Last Post: 12-17-2001, 11:34 AM
  4. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM
  5. Newton-Raphson number squaring method/pointers
    By inakappeh in forum C Programming
    Replies: 2
    Last Post: 08-29-2001, 11:04 AM