Float or double for financial calculations is bad. When coding in C#, use Decimal.

Athanasios Emmanouilidis
Level Up Coding
Published in
2 min readJun 28, 2023

--

Using float or double type for financial calculations in C# (and other languages) may result in wrong calculations. This is because float and double represents numbers in base 2: only numbers which can be expressed in base 2 will be represented precisely. Numbers with a fractional component such as 5.555, 4.333 which are expressed in base 10 will not be represented precisely.

For example:

using System;

float a = 5.555f;
float b = 4.333f;
// The following displays 9.8880005 to the console
Console.WriteLine(a + b);

Will print out the number 9.8880005 which is wrong. The correct number should be 9.888.

The solution? Use Decimal. Decimal represents numbers in base 10 so it can correctly represent numbers expressed in base 10 and its factors (base 2, base 5).

using System;

decimal a = 5.555m;
decimal b = 4.333m;
// The following displays 9.888 to the console
Console.WriteLine(a + b);

This will correctly print 9.888.

That’s it! You now know what type to use on your next project when doing financial calculations.

That was the end of the article! If you have any thought or questions on the article, feel free to leave a comment. If you found the article useful and want to read more like this, be sure to follow me! Also please share it with people you think will benefit from it. See you on the next one!

--

--

Software Engineer @ Intelligen, Inc. Specializes in Microsoft's .NET stack and related technologies. Cybersecurity enthusiast.