2

I have a sql database, it has a column of floats. In it, the value is "4" and it is displayed a "4" while other values are 2.5, 3.6, all have decimals and those seem to function fine for my issue. But the number without a decimal is different.

I have a basic function

  Private Function getScore(scoreValue As Double) As String
    If (scoreValue = 5) Then
        Return "Platinum"
    ElseIf scoreValue >= 4 Then
        Return "Gold"
    ElseIf scoreValue >= 3 Then
        Return "Silver" 
    ElseIf scoreValue >= 2 Then
        Return "Bronze"
    Else
        Return "Unsatisfactory"
    End If

End Function

When i pass this "4" that's a float, it returns the "silver" score. How am i to do this function correctly, i can't round the score, so i can't cast it as an integer. I did various debug statements to figure out what was going on and when i output scoreValue - 4 it yielded 4.44089209850063E-16

Brandon
  • 23
  • 2
  • 1
    I realize, this column should probably be a decimal. – Brandon Dec 31 '14 at 13:19
  • Did it really give 4.44089209850063E-16? Or did it give -4.44089209850063E-16? In the former case, you have a number larger than 4, and if your function returns "Silver", that seems like a bug. In the latter case, you have a number smaller than 4, and if your function returns "Silver", that seems like the correct result. Either way, the problem isn't with your function, it's with earlier calculations that give you such misleadingly close-to-integer numbers. –  Dec 31 '14 at 13:21
  • 1
    4 - myfloat gave the positive number, so my number is essentially 3.999999999999 – Brandon Dec 31 '14 at 13:35
  • Ah, okay, it's just that you have it the wrong way around in the question: you have scoreValue - 4 in your question rather than 4 - scoreValue. –  Dec 31 '14 at 13:53

1 Answers1

1

If you are not going to change the whole application and are focused on this method, you can use Math.Round:

scoreValue = Math.Round(scoreValue, 2, MidpointRounding.AwayFromZero)

This will round the number, but not to an integer - it should keep some meaningful scale.

Either way, you should also consider the scoreValue = 5 condition: it might also fail. See also: Comparing double values in C#

Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • 1
    That was what i ended up doing, but it felt hackish (though i wasn't aware of the midpointrounding either, so that was good to know). If i were to edit it, should it be a decimal then for a small number like this (the values should be between 0 and 5 and really 2 decimals is all that is significant) – Brandon Dec 31 '14 at 13:28
  • @Brandon - Well, it is somewhat hackish. For this code you can also round to `int` and have a specific check for 5. – Kobi Dec 31 '14 at 13:30