Satvir Singh - 5 months ago 9x

Vb.net Question

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

Answer

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
```

Source (Stackoverflow)

Comments