excel - 如何在 Double 上始终保留 2 位小数
问题描述
我有一个宏,它遍历文本列表,提取美元金额,将它们增加 12%,然后用更新的美元金额替换文本。
例如,我需72.8
要这样做72.80
。
有时结果只有 1 位小数,有时只有 3 位。该Round
函数对我来说很好,可以将结果截断到小数点后 2 位,但无助于添加 0 以将数字保持在小数点后两位。
如果结果只有一个小数位,我需要一种方法来用 0 填充第二个小数位。
这是宏:
Function onlyDigits(s As String) As String
' Variables needed (remember to use "option explicit"). '
Dim retval As String ' This is the return string. '
Dim i As Integer ' Counter for character position. '
' Initialise return string to empty '
retval = ""
' For every character in input string, copy digits to '
' return string. '
For i = 1 To Len(s)
If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= "9" Then
retval = retval + Mid(s, i, 1)
End If
Next
' Then return the return string. '
onlyDigits = retval
End Function
Sub ChangeDollarAmount()
Dim qtyspec As String
Dim previousDollarIndex As Integer
Dim dollarSignCount As Integer
Dim dollarString As String
Dim originalDollarAmount As String
Dim changedDollarAmount As Double
Dim isANumber As Boolean
previousDollarIndex = 1
' row count
lastrow = ActiveSheet.Range("A1").CurrentRegion.Rows.Count
For Each cell In Range("K2:K" & lastrow)
Debug.Print cell.Formula
previousDollarIndex = 1
qtyspec = cell.Formula
dollarSignCount = (Len(cell.Formula) - Len(Replace(cell.Formula, "$", ""))) / Len("$")
' loop through dollar amounts in text
For i = 1 To dollarSignCount
isANumber = False
previousDollarIndex = InStr(previousDollarIndex + 1, cell.Formula, "$")
originalDollarAmount = Mid(cell.Formula, previousDollarIndex, 8)
Do While isANumber = False
If Not IsNumeric(Right(originalDollarAmount, 1)) Then
originalDollarAmount = Left(originalDollarAmount, Len(originalDollarAmount) - 1)
Else
isANumber = True
End If
Loop
' extract only digits from dollar amount ($345.23 -> 34523)
dollarAmount = onlyDigits(originalDollarAmount)
' add decimal point and increase dollar amount by 12% (34523 -> 345.23 -> 386.66)
changedDollarAmount = Round(CDbl(dollarAmount) * 1.12 * 0.01, 2)
' update the dollar amount in the text
cell.Formula = Replace(cell.Formula, originalDollarAmount, "$" + CStr(changedDollarAmount))
Next i
Next cell
End Sub
解决方案
changedDollarAmount = CDbl(dollarAmount) * 1.12 * 0.01
cell.Formula = Replace(cell.Formula, originalDollarAmount, Format$(changedDollarAmount, "$0.00"))
推荐阅读
- css - 如何选择属性值为奇数的所有元素
- amazon-web-services - 对 AWS S3 存储桶的访问受限
- c# - 在服务器上使用 C# 打印文件
- c# - 从列表中生成 xml 文件在 mvc C# 中预定义的模式
- python - 在 Python Click 中对帮助输出进行分类
- javascript - JavaScript 中的一等函数和 C++ 中的函数声明
- qt - 有没有办法用QML TextEdit 的 selectedText 属性中的替代文本替换标签
- r - 选择表中的行,然后提取键并在另一个表中搜索并在 R 中显示行闪亮
- typescript - TypeScript 编译器 API 获取映射属性的类型
- python - 在发布 API 之前休眠 X 秒 - Python