"int a = 0.05" but "a - 0.05 = 7.45058e-008"

#include <iostream>
#include <math.h>

using namespace std;

float dolamt;

int main()
{
cout << "Give me an amount less than 1 dollar: ";
cin >> dolamt;

if (dolamt == 0.00)
cout << "nothing" << endl;
if ((dolamt > 0.00) && (dolamt <= 0.01))
cout << 1 * dolamt * 100 << " Penny" << endl;
if ((dolamt > 0.01) && (dolamt < 0.05))
cout << 1 * dolamt * 100 << " Pennies" << endl;
if ((dolamt >= 0.05) && (dolamt <= 0.10))
cout << "1 Nickle and " << ((dolamt - 0.05) * 100) << " Pennies" << endl;


return 0;
}


This is my program so far. I am trying to compute the number of quarters, dimes, nickels, and pennies needed, given an amount (less than $1.00). My problem right now is that when I enter 0.05, I get "1 Nickle and 7.45058e-008 Pennies. Why is it not 0 pennies? If dolamt = 0.05, then 0.05-0.05 should be 0 right?

Also, I am assuming there is a better way of doing this. Anyone want to tell me what I can do to make this easier?
Last edited on
Floating point types (float/double) only have so much precision. 7^-8 is pretty darn close to zero though.
Ok. I just want to get it right though. I don't want it to say "1 Nickle and almost 0 pennies." I want 0. Is there a way to change what I have done to make it like that?
Put lower case f in there
1
2
3
4
float ft;
cin >> ft;
if (ft == .01f)
	cout << "One Penny";
Last edited on
Using == on floating point numbers are generally not a good idea. If I was to do something like this I would store the money as an integer number representing the number of pennies or nickles, whatever is smallest (I don't really know this currency). When you have that you can easily calculate the number of dollars etc. without any rounding errors.
As Pete says, use integers. That's what professional accounting tools do.
I always thought the professionals kept those 1/100 pennies to themselves.
Last edited on
Unless there's good reason to do otherwise (for example, if you need to do currency conversion or other complex financial operations), don't use floating point numbers to store monetary amounts. Use integers and store the number of the smallest unit in the system (e.g. cents). So for example, 100 could represent $1.

The problem with floating point is that it's based on binary encoding, and many common fractional values in currencies, such as 0.01, 0.05, and 0.10, are repeating decimals in binary, meaning floating point representations can't store them exactly in finite memory.
Let's take 1/3 as an example. This is ~0.33333333 in decimal. If we multiply that number by 3 to try and get 1.0 again, we actually get 0.99999999 which is close but not exactly 1. Why? Because we can't write or calculate an infinite number of digits.

0.1 in decimal is 0.000110011001100110011... in binary. It's an infinitly repeating number so if we try and convert that back to decimal, we won't get exactly 0.1 anymore.

Topic archived. No new replies allowed.