1

I am doing some math with doubles in C#. There's a piece of my code:

for(int i = 0 ;; i++){
        double step = num / Math.Pow(10,i + 1);
        step = step - Math.Floor(step);
        step = step * 10;
        Console.WriteLine(step + " " + Math.Floor(step));
        ...
}

So, I get that problem when num equals 14. In the first iteration (i equals 0) Console.WriteLine gives an output 4 3, which means Math.Floor(4) returned 3. Is it some double type problem or what?

Sergei M
  • 11
  • 4
  • Recognise that 1/10 (0.1) can't be expressed exactly in binary, in the same way that 1/3 (0.3 recurring) can't be expressed exactly in decimal. 14 / 10 = 1.4, which has a fractional value of 0110011001100110011 (and so on) in binary. – ProgrammingLlama Aug 26 '20 at 09:44
  • 1
    please, inspect `Console.WriteLine(step.ToString("R"));` - `double` without any rounding; you may want to look at fractional part: `step % 1` – Dmitry Bychenko Aug 26 '20 at 09:46
  • Since you're doing arithmetic in base 10, consider using the `decimal` type instead, since they're better suited to base 10 numbers. – Hans Kilian Aug 26 '20 at 09:49

0 Answers0