0

I'm trying to use the std::map where the is double or float up to the third digit after the decimal point, my problem is how to system save the double number when I'm entering 9.20 some time is saved as 9.199999 and then the find function is not working. is there a way to make it work or just use ints or strings as key?

yaodav
  • 1,126
  • 12
  • 34
  • 6
    Read [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – molbdnilo Dec 22 '19 at 08:20
  • 6
    Use int with a scaling factor (1000) ? – Paul R Dec 22 '19 at 08:31
  • @PaulR do you mean int key = mynum*1000? – yaodav Dec 22 '19 at 08:39
  • 1
    @yaodav Yes, `9.20` should be treated as `9200`, `9.205` as `9205`, etc. Integer types represent numbers accurately, floating point types do not. But it is not as simple as just multiplying, you also need to handle the inaccuracy, so you will need something more like `key = (mynum + 0.0001) * 1000` instead so that `9.199999` becomes more like `9.200099`, and then the multiplication can truncate off the unused digits at the end. – Remy Lebeau Dec 22 '19 at 09:32
  • 1
    Be a bit careful here, what @yaodav means is multiply with 1000 and then cast to the _nearest_ integer. This can still be [problematic](https://stackoverflow.com/q/9695329/8344060). My suggestion would be to use `std::round(f*1000)` as a key since a double can exactly store all integers upto 2^52. So you will not have rounding issues there. – kvantour Dec 22 '19 at 09:40
  • [Ways around using a double as a key in a std set/map](https://stackoverflow.com/q/31121349/995714), [Reliably using doubles as std::map keys](https://stackoverflow.com/q/24937085/995714) – phuclv Dec 22 '19 at 12:42

0 Answers0