2
06/11/2024 6:54 pm
Topic starter
Why is that 0.1+0.1+0.1+0.1... (1000 times) is NOT 100 as a result in C#, but instead I am getting 99.99905?
1 Answer
2
06/11/2024 6:55 pm
It depends on wha tyou are using - if you are using float as a numerical data representation you will get the number mentioned above;
However - you also have double and decimal... Here is my code (with float, double and decimal) - and I am having 100 as a result! 🙂 Test it yourself!
using System; class ZeroPointOne { static void Main() { float sumfloat = 0f; for (int i = 0; i < 1000; i++) { sumfloat = sumfloat + 0.1f; } Console.WriteLine("Sum Float = {0}", sumfloat); ///////////////////////////////////////// double sumdouble = 0d; for (int i = 0; i < 1000; i++) { sumdouble = sumdouble + 0.1d; } Console.WriteLine("Sum Double = {0}", sumdouble); ///////////////////////////////////////// decimal sumdecimal = 0m; for (int i = 0; i < 1000; i++) { sumdecimal = sumdecimal + 0.1m; } Console.WriteLine("Sum Decimal = {0}", sumdecimal); } }