PowerShell文件大小格式化取整原理及VBA实现方法咨询
PowerShell字节转MB的取整逻辑原理
- 首先明确PowerShell中
1mb的定义:它代表1048576字节(即2^20,是二进制体系下的"兆字节",也就是常说的MiB,但PowerShell简化标注为MB)。 - 取整核心是
[int]强制类型转换:当把带小数的数值转换为int类型时,PowerShell会直接截断小数部分,只保留整数位,不会做四舍五入。 - 以你的例子验证:
- 19099648 ÷ 1048576 = 18.2109375,截断小数后得到18,最终输出
18 MB - 12054528 ÷ 1048576 = 11.49609375,截断后得到11,最终输出
11 MB
- 19099648 ÷ 1048576 = 18.2109375,截断小数后得到18,最终输出
VBA实现Windows资源管理器风格的文件大小转换
Windows文件资源管理器的显示逻辑是:使用二进制单位(1MB=1048576字节),并根据数值大小保留对应小数位数(比如MB级通常保留1位小数)。以下是具体实现代码:
基础版:仅转换为MB格式
Function ConvertBytesToMB(ByVal byteCount As LongLong) As String Dim mbValue As Double ' 二进制MB转换系数:1024*1024=1048576 mbValue = byteCount / 1048576 ' 四舍五入到1位小数后拼接单位 ConvertBytesToMB = Format(mbValue, "0.0") & " MB" End Function ' 调用测试 Sub TestMBConversion() Debug.Print ConvertBytesToMB(19099648) ' 输出:18.2 MB Debug.Print ConvertBytesToMB(12054528) ' 输出:11.5 MB End Sub
进阶版:自动适配单位(Bytes/KB/MB/GB)
模拟资源管理器自动切换单位的逻辑,根据文件大小选择最合适的单位并调整小数位数:
Function FormatFileSize(ByVal byteCount As LongLong) As String Dim sizeValue As Double Dim unit As String ' 根据字节数选择对应单位 Select Case byteCount Case Is < 1024 sizeValue = byteCount unit = " Bytes" Case Is < 1024 ^ 2 sizeValue = byteCount / 1024 unit = " KB" Case Is < 1024 ^ 3 sizeValue = byteCount / (1024 ^ 2) unit = " MB" Case Else sizeValue = byteCount / (1024 ^ 3) unit = " GB" End Select ' 适配资源管理器的小数显示规则:小单位保留整数,大单位保留1位小数 If unit = " Bytes" Or unit = " KB" Then FormatFileSize = Format(sizeValue, "0") & unit Else FormatFileSize = Format(sizeValue, "0.0") & unit End If End Function ' 调用测试 Sub TestAutoFormat() Debug.Print FormatFileSize(19099648) ' 输出:18.2 MB Debug.Print FormatFileSize(12054528) ' 输出:11.5 MB Debug.Print FormatFileSize(1450) ' 输出:1 KB Debug.Print FormatFileSize(2100000000) ' 输出:1.9 GB End Sub
内容的提问来源于stack exchange,提问作者darekk
相关产品推荐
相关产品推荐

