Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal places in a number in VB.NET

Tags:

decimal

vb.net

How do I check how many decimal places a number has in VB.NET?

For example: Inside a loop I have an if statement and in that statement I want to check if a number has four decimal places (8.9659).

like image 593
Lumart Avatar asked Oct 30 '11 19:10

Lumart


2 Answers

A similar approach that accounts for integer values.

Public Function NumberOfDecimalPlaces(ByVal number As Double) As Integer
    Dim numberAsString As String = number.ToString()
    Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")

    If indexOfDecimalPoint = -1 Then ' No decimal point in number
        Return 0
    Else
        Return numberAsString.Substring(indexOfDecimalPoint + 1).Length
    End If

End Function
like image 109
vroc38 Avatar answered Sep 19 '22 22:09

vroc38


Dim numberAsString As String = myNumber.ToString()
Dim indexOfDecimalPoint As Integer = numberAsString.IndexOf(".")
Dim numberOfDecimals As Integer = _
    numberAsString.Substring(indexOfDecimalPoint + 1).Length
like image 38
Dennis Traub Avatar answered Sep 21 '22 22:09

Dennis Traub