Hello,
I am working on a project where I have the user to input a value and I am storing it in a float variable. However, the value that is getting stored in the variable isn't the exact value the user input. For example, if the user entered 399.975, the value that is actually stored is 399.97501. By any chance do anyone knows why this is happening?
Thanks In Advance
The float data type is an approximation. http://en.wikipedia.org/wiki/Floating_point_numbers.
Remember that the fractional portion of a floating point number has to be converted from decimal to binary. Not all fractions can be precisely represented in binary.
To be precise, the value actually stored is 399.975006103515625 (exactly 13106381 * 2-15), which is the closest valid float to what you entered. The number 399.975 cannot be represented as a float: it lies between that value and 399.9749755859375 (exactly 13106380 * 2-15), but is slightly closer to the former.
Use doubles if you're concerned with that level of granularity, you'll get 399.9750000000000227373675443232059478759765625
I assume you mean you want to limit the precision when outputting the numbers. Yes you can. See the following page (http://www.cplusplus.com/reference/iomanip/setprecision/) to see how to set floating point precision while using ostreams.