Android Code Snippet Shorten numbers

Hi
I programing function for short number
Example convert 1000 to 1k or 1500 to 1.5k
Enjoy it (if i made a mistake,develop it)

B4X:
Sub ShortenNumber(Value As String) As String
   
    Dim formatted As String
   
    If Value >= 1000 And Value < 1000000 Then
       
        If Value Mod 1000 = 0  Then
            formatted = (Value/1000)
        Else
            formatted = Value / 1000
        End If
       
        formatted = formatted & "k";
   
    Else if Value > 999999 Then
        formatted = (Value/1000000) & "M"
    Else
        formatted = Value
    End If
   
    Return formatted
   
End Sub
 
Last edited:

MarkusR

Well-Known Member
Licensed User
Longtime User
my version of it
B4X:
Sub ShortenNumber(Value As Float) As String
  
    'https://en.wikipedia.org/wiki/Unit_prefix
  
    Dim unitprefix As String
  
    If Value >= 1000000.0 Then

        Value = Value / 1000000.0
        unitprefix ="M"

    Else If Value >= 1000.0 Then
        
        Value = Value / 1000.0
        unitprefix = "k"
  
    End If
  
    Return NumberFormat( Value ,1,2) & unitprefix
  
End Sub
 
Top