floating point and rounding

I'm beginning to learn C, and have found some of the little problems associated with floating point. I was wondering though, what would be a good way to do calculations involving money and other decimal numbers? Also, how would you go about rounding certain decimal places? Thanks in advance.

Comments

  • [code]
    float Before = 113.32435;
    float After;

    After = ((int)(100.0f*Before))/100.0f;

    /* After now equals 113.32 */
    [/code]
    In every situation I've seen, truncating by converting to an int is faster than fmod (in math.h), that's why I use it.

  • Because of the limitations of floating point calculations and because calculations involving currency normally treat it as a fixed amount (you don't have to deal with varying decimal places) it can be easier to work with integers. Use a different integer variable for different currency denominations.

  • : [code]
    : float Before = 113.32435;
    : float After;
    :
    : After = ((int)(100.0f*Before))/100.0f;
    :
    : /* After now equals 113.32 */
    : [/code]
    : In every situation I've seen, truncating by converting to an int is faster than fmod (in math.h), that's why I use it.
    :

    I see what you are doing here. You make an integer, and then divide by 100 to do the float. What I don't understand in this line --

    > After = ((int)(100.0f*Before))/100.0f;

    is the f after 100.0. What is that?


  • Any number with a decimal is considered a double by default. We don't need a double, so I use the 'f' to force it to be a float. A lot of people don't know about the 'f' suffix, I get asked what they're for a lot ;).

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories