I am beginner in C# and I am working with floating point numbers. I need to do subtraction between these two numbers but it does not work. I know it is caused by floating point number, but how can I fix it please and if you be so good can you explain me why is it happening? Thanks in advance.
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
Consider using decimal instead of float:
// Instead of this...
float a = 12.345F;
float b = 12;
float c = a - b;
// Use this:
decimal d = 12.345M;
decimal e = 12;
decimal f = d - e;
Jon Skeet gives a good explanation of the differences between both types in this answer: https://stackoverflow.com/a/618596/446681
This is not a c# problem, this is a computer science problem. If you want to truly understand what is going on, read What Every Computer Scientist Should Know About Floating-Point Arithmetic. If you just care about why you're having the problem, it's because Float and Double are only precise to 7 and 15 digits respectively on this platform, and you need to apply rounding logic to achieve the result you are looking for.
Float C# reference
Double C# reference
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation. Goldberg 1991
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With