0

I'm working to find the position of the first none-zero digit after the decimal point

So far I have managed to find the number of decimal digits using

Dim value As Single = 2.0533
Dim numberOfdecimaldigits As Integer = value.ToString().Substring(value.ToString().IndexOf(".") + 1).Length
MessageBox.Show(numberOfdecimaldigits)

if I have 4.0342, then I'm looking to get 2 for the position of 3 after the decimal value. What I want to do with this data, is to add 2 to the whole number depending on the location of the none-zero digit. For example: for 4.0342, I want the system to add 0.02 to it. If it's 5.00784, then I want to add 0.002 to it.

Is there a way to know the position of first none-zero digit after the decimal point?

Thank you in advance

Satvir Singh
  • 61
  • 4
  • 16

2 Answers2

2

I strongly recommend not using strings here — you are performing a numerical algorithm, it’s more direct and more efficient to work on the number using numeric logic:

value = value - Math.Floor(value) ' Get rid of integer digits
Dim position = 0

While value > 0 AndAlso Math.Floor(value) = 0
    value = value * 10
    position += 1
End While

If value = 0 Then Throw New Exception(…)
Return position
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

Here is my take on the matter which prevents an infinite loop

value = value - Math.Floor(value) ' Get rid of integer digits

If value = 0 Then Throw New Exception(...)

value = 1/value ' Invert the value
Dim position = 0

While value > 1
    value = value / 10
    position += 1
End While

Return position
Alexandre ELIOT
  • 146
  • 1
  • 9