1

I'm trying to check if a given number is 2 or 3 digit after the decimal point, I tried a few methods but non but one was good: the first one is -

bool Is2DecimalPlaces(double num) {
      double value = num * 100;
      auto ans = (value == std::floor(value));
      return  ans;
}

but on input 10.12 and 10.13 it gives the wrong answer, I tried using decimal::decimal64

bool Is2DecimalPlaceString(double num) {
  std::decimal::decimal64 var(num);
  return std::decimal::decimal64(std::floor(num * 100)) == (var *= 100);
}

also not working the only method that works every time is co convert to string and check if the third place after the decimal point in '0' but it's not very efficient.

tried using this answer from here with no luck

this is my test case

Deepak Patankar
  • 3,076
  • 3
  • 16
  • 35
yaodav
  • 1,126
  • 12
  • 34
  • 2
    Floating point math is not exact. Take a look at [Is floating point math broken?](https://stackoverflow.com/q/588004/5910058) and [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Jesper Juhl Jul 27 '20 at 15:40
  • 1
    Obligatory [Tom Scott video](https://www.youtube.com/watch?v=PZRI1IfStY0). – G. Sliepen Jul 27 '20 at 15:48

1 Answers1

0

As mentioned in the first comments, due to accuracy reasons you can't rely on floating point arithmetic to calculate the number of decimals of a floating point number.

Therefore, I'd advise you to work in another way (I assume those numbers are coming from some source, be it a database, a file or a user input)?
Then use two versions of that number:

  • The version as you have read it, but read it as a string, not a number (you can use this for calculating the decimals).
  • The version where you have converted that string into a floating point number (you can use this for other basic floating point arithmetic).
Dominique
  • 16,450
  • 15
  • 56
  • 112
  • your ware correct in your assumption that I'm getting those numbers but I'm getting them as doubles so Il have to convert them manually and then check them – yaodav Jul 27 '20 at 16:36
  • @yaodav: that's my point: here you can say that technical limitations need you to get those numbers as strings, not as doubles, hence the one, providing you with these numbers, needs to do some adaptation (you have a technical, correct reason to request this). – Dominique Jul 27 '20 at 16:53