VB6

Hi,
  How to use format to chop off the long trail decimal without rounding (up and down ) it and up to 2 decimals only?

 e.g -  343.236788976
 to be  343.23 NOT 343.24


TQ!.
wzmAsked:
Who is Participating?
 
ronkleinConnect With a Mentor Commented:
hi,

here's a little code snippet.
the function is the main core here.
all the other stuff is just for a nice demo for the output itself.
enjoy...

note, however, that the function could be better (in terms of performance) if you have a predefined array of formats for the given argument DigitsAfter, instead of creating the correct format for each call. if you wish - please reply and i'll rewrite the code.

best regards,

-Ron

Public Function DecimalFormat(Number As Double, DigitsAfter As Byte) As String
    Const MAX_DIGITS_ON_THE_RIGHT_SIDE As Byte = 10
   
    Dim strFormat As String
    Dim bytIndex As Byte
    Dim lngLength As Long
   
    'check that we're in a valid context. raise an error if not...
    If (DigitsAfter > MAX_DIGITS_ON_THE_RIGHT_SIDE) Then
        Err.Raise vbObjectError + 1, "DecimalFormat", "'DigitsAfter' cannot exceed " & CStr(MAX_DIGITS_ON_THE_RIGHT_SIDE)
    End If
   
    'special case of zero
    If (0 = DigitsAfter) Then
        DecimalFormat = Format(Number, "#")
        Exit Function
    End If

    'prepare the format string
    'initialize
    strFormat = "#."
    For bytIndex = 0 To DigitsAfter
        strFormat = strFormat & "0"
    Next

    DecimalFormat = Format(Number, strFormat)
    lngLength = Len(DecimalFormat)
    If (lngLength > 0) Then
        DecimalFormat = Left(DecimalFormat, lngLength - 1)
    End If
End Function

Private Sub Command1_Click()
    Dim dblDemoValue As Double
    Dim strTemp As String
    Dim bytIndex As Byte
   
    dblDemoValue = 123.456789
   
    bytIndex = 0
    strTemp = "DecimalFormat(" & dblDemoValue & ", " & bytIndex & ") = " & DecimalFormat(dblDemoValue, bytIndex)
    For bytIndex = 1 To 9
        strTemp = strTemp & vbNewLine & "DecimalFormat(" & dblDemoValue & ", " & bytIndex & ") = " & DecimalFormat(dblDemoValue, bytIndex)
    Next
   
    MsgBox strTemp
End Sub
0
 
omegaomegaDeveloperCommented:
Hello, w2m,

I would use:

    Dim strResult As String
    strResult = Format(dblValue, "#0.000")
    strResult = Left(strResult, Len(strResult) - 1)

Another possibility would be:

    Format(Fix(100 * Value) / 100, "#0.00")

"Fix" returns the integer equal to or closer to zero than the argument.  Depending on how you want to deal with negative numbers you might want to use "Int" instead of "Fix".  "Int" returns the integer less than or equal to the argument.  (The above will "truncate" -123.456 to -123.45 whereas if "Int" is used it will return -123.46.)  

Cheers,
Randy
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.