TheMrDrake
TheMrDrake

Reputation: 11

Getting Cents from Math C++

Right now my code works just that when I get I print out he cents i am off by one because of the the round error the compiler does when you take say 0.95 * 100 it gives me 94 or something that is not 95. I know how the math works to get it normally but with this rounding error I can't do it.

Also don't worry about asking me why I am using C and C++ at the same time. Its because this is how my instructor wanted it.

Here is the relevant code.

if (dollarAmount < 10.00 && dollarAmount >= 1.00)
{
    cents = (dollarAmount - static_cast<int>(dollarAmount)) * 100;
    digit = (((static_cast<int>(dollarAmount)/ 1)));

    strcat(amountInWords, lookUp[digit]);
    strcat(amountInWords, " dollars and ");

}

Whole project code: https://gist.github.com/anonymous/65c052277c67f03de643

Upvotes: 0

Views: 639

Answers (2)

Lacuno
Lacuno

Reputation: 464

Don't use floating point variables when rounding is important. Just use a long variable to store cents.

Upvotes: 4

Vilx-
Vilx-

Reputation: 106912

Use round() instead of static_cast<int>. The difference between the actual value and what fits inside your float is 0.0000000somethingsmall. Rounding will always give the correct answer.

Also, round only after multiplying by 100.

Upvotes: 1

Related Questions