-1

I need a double value to contain 2 digits after ".", such as 2.15, 20.15. If the input value is 3.125, then it should print an error message.

My code is:

    private static bool isTwoDigits(double num)
    {
        return (num - Math.Floor(num)).ToString().Length <= 4;
    }

If you input 2.15, then it will be 2.15 -2 = 0.15 <= 4 - which works. But when I change num to 20.15 it doesn't, because (num - Math.Floor(num)) here will return 0.14999999999.

Any other good ideas?

Mark Bertenshaw
  • 5,594
  • 2
  • 27
  • 40

3 Answers3

1

This is the nature of binary floating points number. Just like 1/3 can't be exactly written out as a finite decimal number, 0.1 can't be exactly represented by a finite binary expansion.

So depending on what you are trying to achieve exactly, you could:

  1. If you are validating some string input (e.g. a textbox), you can process the information at the string level, e.g. with a RegEx.

  2. You can store your numbers in the decimal datatype, which can store decimal values exactly.

  3. You can do your computation on a double but you have to give yourself a tolerance. If you expect only 2 digits of precision, you can do something like Math.Abs(x - Math.Round(x, 2)) < 0.00000001). The definition of this tolerance margin depends on your use case.

jods
  • 4,581
  • 16
  • 20
0

If you're really worried about the number of decimal places, on a base-10 number, use decimal instead of double.

the decimal is for calculating financial calculations, and the reason it's called decimal in the first place is so that it can better handle base-10 calculations such as dollars and cents.

And you can also check if the number is 2 digits a bit more simply.

return num % 0.01m == 0.0m;
0

SO as has already been said, you can use regexp to ensure the entire format is correct.

But if you know there will only be 1 decimal because its already a number you can also just use String.IndexOf

eg

double foo = ....  ;
string fooString = foo.ToString();
if (fooString.Length - fooString.IndexOf(".") != 3)  => error.

(Its 3 because Length is max index + 1 )

user430788
  • 2,143
  • 2
  • 17
  • 17