Truncating Double with VBA in excel

前端 未结 4 1217
刺人心
刺人心 2021-01-04 05:21

I need to truncate the amount of decimal places of my double value for display in a textbox. How would one achieve this with vba?

4条回答
  •  -上瘾入骨i
    2021-01-04 05:34

    If you want to round the value, then you can use the Round function (but be aware that VBA's Round function uses Banker's rounding, also known as round-to-even, where it will round a 5 up or down; to round using traditional rounding, use Format).

    If you want to truncate the value without rounding, then there's no need to use strings as in the accepted answer - just use math:

    Dim lDecimalPlaces As Long: lDecimalPlaces = 2
    Dim dblValue As Double: dblValue = 2.345
    
    Dim lScale = 10 ^ lDecimalPlaces
    Dim dblTruncated As Double: dblTruncated = Fix(dblValue * lScale) / lScale
    

    This yields "2.34".

提交回复
热议问题