1

My user enters values as floating point numbers(dollars and cents) and I am trying to perform accurate calculations with their input. To do this, the goal is to multiply their input by 100 and convert it to an integer. However, when I try to use cin to get their input as a double, it is not stored accurately ie. if they enter 15.03, the value is stored as 15.0299999999(based on debugging the code). While this is not a problem for my test cases, I foresee corner cases where rounding errors cause strange issues. Given that I am simply performing 2 decimal point calculations, is there a way around this? My code is below:

double ammount_spent; 
cin >> ammount_spent; 
int cents_spent=100*ammountspent; 
cout cents_spent; 
Teererai Marange
  • 1,830
  • 3
  • 26
  • 45
  • Why multiply by 100 to begin with? You can't work witb doubles everywhere? – Ivan Rubinson Oct 25 '16 at 05:38
  • 4
    Accept currency as two ints instead of one double. – StoryTeller - Unslander Monica Oct 25 '16 at 05:38
  • or you can accept as string, and parse it later. – rcs Oct 25 '16 at 05:45
  • 1
    15.03 can't be represented exactly as floating point, 15.0299999999 is the nearest `double`. Use integers. – molbdnilo Oct 25 '16 at 05:53
  • You can introduce epsilon to create confidence threshold like a == b is true if (a > b - epsilon and a < b + epsilon) – khôi nguyễn Oct 25 '16 at 05:54
  • 1
    I run code given by you..If i give input 15.03 then its storing value as 15.0299999999, that's true.But at the end it prints 1503 as answer. May i know where you find issue? – RDX Oct 25 '16 at 05:55
  • Below code prints true: if (ammount_spent == 15.03) { cout << "true" << endl; } – RDX Oct 25 '16 at 05:55
  • @RDX the code will run into trouble if http://ideone.com/yIMgRy – khôi nguyễn Oct 25 '16 at 05:58
  • @khôinguyễn..That's expected..for declaring variable as float you need to defined as "float varName1 = 15.03f" without that appending "f", value treated as double.. so "double varName2 = 15.03f" and "float varName1=15.03f" are same. – RDX Oct 25 '16 at 06:06
  • take a look here http://stackoverflow.com/questions/15319967/exact-decimal-datatype-for-c – Evgeniy Oct 25 '16 at 06:27
  • `double` is a waste of time here. Unless this is Superman III, you aren't going to have half pennies. Go fixed point and do all the math and comparisons in pennies. Convert to dollars for display – user4581301 Oct 25 '16 at 06:31
  • Why don't you let them enter dollars separately from cents. `cin >> dollars_spent >> cents_spents` and proceed from there – Paa K Oct 25 '16 at 06:42
  • I cant do that because the user enters values in that specific format. it's to solve the trip programming challenge – Teererai Marange Oct 26 '16 at 01:43

0 Answers0