cout'ing a float

Hey yall, another question. So I'm trying to output a float in a cout statement, and it keeps giving me extra numbers on the end, specifically 012142. The float is coming from a private member of my class and is supposed to be a price of a game, so let's say I wanna cout the price of the app and the price is 100, ill get 10012142. The prices are different for each app, but I don't have to worry about cents. I'm pretty sure there's an easy function that'll help me out with this but I really can't remember it for the life of me. Any tips or help would be appreciated, I would attach some code but it would be a lot since it's an object that's getting put into a map, and then the price is getting called from there.
Please show us the most essential bits of the code. How else could anyone explain what your program does?
Last edited on
floats and doubles are not precise.
for money, or things like that, I recommend you use integers that represent pennies or whatever your smallest denomination unit is, and then just print it as if it had a decimal.
to do that, there are various ways, a simple one is
cout << price/100 << '.' << price%100;
if you don't ever have any cents, then you can use smallest unit = $1 instead, and just print the value directly as an integer.
Last edited on
The important thing to note about floating-point numbers, e.g. float or double, is that they have a limited precision, but not in the sense that (only) a fixed number of "fraction digits" is preserved 😨

Instead, the number of "fraction digits" that will be preserved depends on how "big" the number is. Simply put, for "smaller" numbers more "fraction digits" are persevered. And for "bigger" numbers fewer "fraction digits" are persevered. For "extremely large" numbers, not even the integral part is preserved accurately!

So, as others have pointed out, floating-point numbers are a bad choice to represent things like money. Therefore, you should go with an integer type that represents the smallest "unit" of money that you need to deal with. Either that, or consider using "arbitrary precision" rational numbers, as provided by GMP:
Last edited on
extra numbers on the end, specifically 012142 ... so let's say I wanna cout the price of the app and the price is 100, ill get 10012142.

On closer look that does not look consistent. Surely, if you print "100" and "012142", then you should get "100012142", not "10012142"?

If you print just one float and it is "bit over 100", then you would see the decimal point: "100.012142"
If you print a newline character '\n' right after the float do the extra digits end up on a new line?

float my_float = 100;
std::cout << my_float << "\n";

If so, then you're probably printing those additional digits from some other part of the code that is executed later.
Last edited on
Topic archived. No new replies allowed.