将字节值转换为 GB/MB/KB,我使用的是 ByteCountFormatter。下面的示例代码。
func converByteToGB(_ bytes:Int64) -> String {
let formatter:ByteCountFormatter = ByteCountFormatter()
formatter.countStyle = .binary
return formatter.string(fromByteCount: Int64(bytes))
}
Run Code Online (Sandbox Code Playgroud)
现在,我的要求是它应该只显示小数点后一位。1.24 GB => 1.2 GB 的示例,而不是 1.24 GB。应用地板或天花板功能后,强制为个位数。
ByteCountFormatter不能只显示小数点后一位。默认情况下,它显示字节和 KB 的 0 个小数位;MB 的 1 个小数位;2 GB 及以上。如果isAdaptive设置为false它尝试显示至少三位有效数字,必要时引入小数位。
ByteCountFormatter还修剪尾随零。禁用设置zeroPadsFractionDigits为true.
我已经改编了如何在 Java 中将字节大小转换为人类可读的格式?做你想做的事:
func humanReadableByteCount(bytes: Int) -> String {
if (bytes < 1000) { return "\(bytes) B" }
let exp = Int(log2(Double(bytes)) / log2(1000.0))
let unit = ["KB", "MB", "GB", "TB", "PB", "EB"][exp - 1]
let number = Double(bytes) / pow(1000, Double(exp))
return String(format: "%.1f %@", number, unit)
}
Run Code Online (Sandbox Code Playgroud)
请注意,这将格式化 KB 和 MB 与ByteCountFormatter. 这是删除尾随零并且不显示 KB 和大于 100 的数字的小数位的修改。
func humanReadableByteCount(bytes: Int) -> String {
if (bytes < 1000) { return "\(bytes) B" }
let exp = Int(log2(Double(bytes)) / log2(1000.0))
let unit = ["KB", "MB", "GB", "TB", "PB", "EB"][exp - 1]
let number = Double(bytes) / pow(1000, Double(exp))
if exp <= 1 || number >= 100 {
return String(format: "%.0f %@", number, unit)
} else {
return String(format: "%.1f %@", number, unit)
.replacingOccurrences(of: ".0", with: "")
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,此实现未考虑 Locale。例如,某些语言环境使用逗号 (",") 而不是点 (".") 作为小数分隔符。
| 归档时间: |
|
| 查看次数: |
4431 次 |
| 最近记录: |