Rounding Floats

This is a discussion on Rounding Floats within the C Programming forums, part of the General Programming Boards category; Hi, I was wondering if anybody knows an easy way to round floats. I wrote a program calculating money, and ...

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    7

    Rounding Floats

    Hi, I was wondering if anybody knows an easy way to round floats. I wrote a program calculating money, and I'd like to display the right amount of decimal places for dollars and cents. Right now, it's printing numbers like "156.945957" and I'd just like it to print "156.95". Thanks in advance.

  2. #2
    Registered User Draco's Avatar
    Join Date
    Apr 2002
    Posts
    463
    if you want to round to a certain decimal amount every time, you can just use the printf conversion.

    [example]
    printf("Random number = %.3f ", floatingnum);
    [\example]

  3. #3
    Registered User
    Join Date
    Jan 2003
    Posts
    115
    you can use printf and specify how much to round up by with %.Nf where N represents how far you want to round off.
    i.e. %.2f will round off to 2 decimal places. %.3f will go to 3 decimal places and so on.
    there are only 10 people in the world, those who know binary and those who dont

  4. #4
    Registered User
    Join Date
    Feb 2003
    Posts
    7

    Smile

    Thanks! It Works!

  5. #5
    still a n00b Jaguar's Avatar
    Join Date
    Jun 2002
    Posts
    187
    Whatabout rounding float and stores it in float variables?
    Normally I write my own function to do this, but any instant functions else?
    slackware 10.0; kernel 2.6.7
    gcc 3.4.0; glibc 2.3.2; vim editor
    migrating to freebsd 5.4

  6. #6
    Registered User pinko_liberal's Avatar
    Join Date
    Oct 2001
    Posts
    284
    Have a look at the functions floor and ceil in math.h
    The one who says it cannot be done should never interrupt the one who is doing it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. rounding off floats
    By creeping death in forum C Programming
    Replies: 6
    Last Post: 04-01-2009, 01:49 PM
  2. rounding off floats
    By cole in forum C Programming
    Replies: 5
    Last Post: 09-29-2008, 04:25 AM
  3. Reading errors in floats
    By Improvolone in forum C++ Programming
    Replies: 8
    Last Post: 03-21-2006, 02:20 PM
  4. Help with rounding a number
    By nickk in forum C Programming
    Replies: 3
    Last Post: 06-02-2004, 11:44 AM
  5. comparing two arrays of floats
    By COBOL2C++ in forum C++ Programming
    Replies: 7
    Last Post: 07-16-2003, 03:22 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21