Source code for Issue Number 52

Copyright 1997-2000 by C&D Programming Corp. All Rights Reserved. Source code may not be reproduced except for use in a compiled executable. All rights reserved. If you would like to reprint any or all of this code please email us at info@codeoftheweek.com

Code of the Week Home


Source Code

Just paste this source code into a module called basFormatting and include it in your project.

'----------------------------------------------------------------------
'
'   Module Name:    basFormatting
'   Written By:     C&D Programming Corp.
'   Create Date:    7/98, 8/98
'   Copyright:      Copyright 1998 by C&D Programming Corp.  Source
'                   code may not be reproduced except for use in a
'                   compiled executable.  All rights reserved.  If
'                   you would like to reprint any or all of this
'                   code please email us at info@codeoftheweek.com
'----------------------------------------------------------------------
Option Explicit

Public Enum eNumberFormat
    nf_BestFit
    nf_Bytes
    nf_KiloBytes
    nf_MegaBytes
    nf_GigaBytes
End Enum

Private Const KILOBYTE = 1024#              ' 1024 Bytes = 1 Kilobyte
Private Const MEGABYTE = 1048576#           ' 1024 * 1024  Bytes = 1 Megabyte
Private Const GIGABYTE = 1073741824#        ' 1024 * 1024 * 1024 Bytes = 1 Gigabyte

'
'   Removes trailing decimal point if there is nothing to the right of the decimal
'
Private Function StripDecimal(sValue As String) As String
    If Right(sValue, 1) = "." Then
        StripDecimal = Left(sValue, Len(sValue) - 1)
    Else
        StripDecimal = sValue
    End If
End Function

Public Function SmartNumberFormat(dblNumber As Double, Optional eReturnType As eNumberFormat = nf_BestFit) As String
    If eReturnType = nf_BestFit Then
        If dblNumber > GIGABYTE Then
            eReturnType = nf_GigaBytes
        ElseIf dblNumber > MEGABYTE Then
            eReturnType = nf_MegaBytes
        ElseIf dblNumber > KILOBYTE Then
            eReturnType = nf_KiloBytes
        Else
            eReturnType = nf_Bytes
        End If
    End If

    Select Case eReturnType
        Case nf_Bytes
            SmartNumberFormat = Format$(dblNumber, "###,###,###")
        Case nf_KiloBytes
            SmartNumberFormat = StripDecimal(Format$(dblNumber / KILOBYTE, IIf(dblNumber = 0, "0KB", "###,###,###.#"))) & "KB"
        Case nf_MegaBytes
            SmartNumberFormat = StripDecimal(Format$(dblNumber / MEGABYTE, IIf(dblNumber = 0, "0MB", "###,###,###.#"))) & "MB"
        Case nf_GigaBytes
            SmartNumberFormat = StripDecimal(Format$(dblNumber / GIGABYTE, IIf(dblNumber = 0, "0GB", "###,###,###.#"))) & "GB"
    End Select
End Function