Reputation: 720
I'm using VB.net 2013 and SQL server 2008R2.
I'm writing a financial application , and I'm not sure about which data type to use.
I know that decimal is more precise than float , but I read that using decimal can significantly decrease the speed of calculations , so the speed of my application. I read that using decimals can be 20 times slower than using float. Is this true , and if yes is there a solution or should I continue to use float ?
Thank you !
Upvotes: 1
Views: 349
Reputation: 26434
Use decimal for financial applications, period. Speed does not matter in this case. When money is lost, your users won't be happy. You cannot argue saying "well, but on the other hand, it was fast". Regarding 20 times difference on float vs decimal, trust me, you won't feel it at all, there will be more major factors in your app's performance. Most likely trying to synchronize transactions between each other, DB locks etc.
EDIT: Regarding 20 times performance difference, this is true, I was able to reproduce with below code:
Module Module1
Sub Main()
Dim f As Single = 123456792.0F
Dim fsw As New Stopwatch
fsw.Start()
For i = 1 To 100000000
f *= 1.00000012F
Next
fsw.Stop()
Dim dsw As New Stopwatch
dsw.Start()
Dim d As Decimal = 123456792.0F
For i = 1 To 100000000
d *= 1.00000012F
Next
dsw.Stop()
Console.WriteLine(f)
Console.WriteLine("Float (ms): " & fsw.ElapsedMilliseconds)
Console.WriteLine(d)
Console.WriteLine("Decimal (ms): " & dsw.ElapsedMilliseconds)
Console.WriteLine("Float is " & dsw.ElapsedMilliseconds / fsw.ElapsedMilliseconds & " faster")
Console.ReadLine()
End Sub
End Module
Output:
While writing this code, I got anywhere between 10-20 times for different numbers. As I mentioned before, speed is not the concern, compare the accuracy of both approaches, notice how float is off by several orders of magnitude. This is, of course, a synthetic example, but it shows how people may end up with 1 dollar on their payroll instead of a 1000 - imagine the reaction.
Upvotes: 5