2

我想减少小数长度

   text1.text = 2137.2198231578

从上面,我只想显示前 2 位十进制数

预期产出

text1.text = 2137.21

这该怎么做。

4

4 回答 4

3
Format("2137.2198231578", "####.##")
于 2012-04-12T08:39:30.763 回答
0

Format()当我注意到 p0rter 评论时,我正要发布使用。

Format(text1.text, "000.00") 

我想Int()会为你四舍五入。

自从我使用VB6以来已经很多年了......

于 2012-04-12T08:35:35.410 回答
0

这个函数应该做你想做的(内联注释应该解释正在发生的事情):

Private Function FormatDecimals(ByVal Number As Double, ByVal DecimalPlaces As Integer) As String
    Dim NumberString As String
    Dim DecimalLocation As Integer
    Dim i As Integer
    Dim LeftHandSide As String
    Dim RightHandSide As String

    'convert the number to a string
    NumberString = CStr(Number)
    'find the decimal point
    DecimalLocation = InStr(1, NumberString, ".")

    'check to see if the decimal point was found
    If DecimalLocation = 0 Then
        'return the number if no decimal places required
        If DecimalPlaces = 0 Then
            FormatDecimals = NumberString
            Exit Function
        End If
        'not a floating point number so add on the required number of zeros
        NumberString = NumberString & "."
        For i = 0 To DecimalPlaces
            NumberString = NumberString & "0"
        Next
        FormatDecimals = NumberString
        Exit Function
    Else
        'decimal point found
        'split out the string based on the location of the decimal point
        LeftHandSide = Mid(NumberString, 1, DecimalLocation - 1)
        RightHandSide = Mid(NumberString, DecimalLocation + 1)
        'if we don't want any decimal places just return the left hand side
        If DecimalPlaces = 0 Then
            FormatDecimals = LeftHandSide
            Exit Function
        End If
        'make sure the right hand side if the required length
        Do Until Len(RightHandSide) >= DecimalPlaces
            RightHandSide = RightHandSide & "0"
        Loop
        'strip off any extra didgits that we dont want
        RightHandSide = Left(RightHandSide, DecimalPlaces)
        'return the new value
        FormatDecimals = LeftHandSide & "." & RightHandSide
        Exit Function
    End If
End Function

用法:

Debug.Print FormatDecimals(2137.2198231578, 2) 'outputs 2137.21
于 2012-04-12T09:50:00.917 回答
0

看起来相当简单,但我必须在这里遗漏一些微妙的东西。关于什么:

Option Explicit

Private Function Fmt2Places(ByVal Value As Double) As String
    Fmt2Places = Format$(Fix(Value * 100#) / 100#, "0.00")
End Function

Private Sub Form_Load()
    Text1.Text = Fmt2Places(2137.2198231578)
End Sub

这也适用于小数点字符为逗号的语言环境。

于 2012-04-12T14:43:28.183 回答