Data Size String: fixed remainder calculation and added customizable decimal separator

This commit is contained in:
Ilya Laktyushin 2019-03-09 22:03:00 +03:00
parent f24d58d7de
commit 621f52fcf4

View File

@ -1,26 +1,26 @@
public func dataSizeString(_ size: Int, forceDecimal: Bool = false) -> String { public func dataSizeString(_ size: Int, forceDecimal: Bool = false, decimalSeparator: String = ".") -> String {
return dataSizeString(Int64(size), forceDecimal: forceDecimal) return dataSizeString(Int64(size), forceDecimal: forceDecimal, decimalSeparator: decimalSeparator)
} }
public func dataSizeString(_ size: Int64, forceDecimal: Bool = false) -> String { public func dataSizeString(_ size: Int64, forceDecimal: Bool = false, decimalSeparator: String = ".") -> String {
if size >= 1024 * 1024 * 1024 { if size >= 1024 * 1024 * 1024 {
let remainder = (size % (1024 * 1024 * 1024)) / (1024 * 1024 * 102) let remainder = Int64((Double(size % (1024 * 1024 * 1024)) / (1024 * 1024 * 102.4)).rounded(.down))
if remainder != 0 || forceDecimal { if remainder != 0 || forceDecimal {
return "\(size / (1024 * 1024 * 1024)),\(remainder) GB" return "\(size / (1024 * 1024 * 1024))\(decimalSeparator)\(remainder) GB"
} else { } else {
return "\(size / (1024 * 1024 * 1024)) GB" return "\(size / (1024 * 1024 * 1024)) GB"
} }
} else if size >= 1024 * 1024 { } else if size >= 1024 * 1024 {
let remainder = (size % (1024 * 1024)) / (1024 * 102) let remainder = Int64((Double(size % (1024 * 1024)) / (1024.0 * 102.4)).rounded(.down))
if remainder != 0 || forceDecimal { if remainder != 0 || forceDecimal {
return "\(size / (1024 * 1024)),\(remainder) MB" return "\(size / (1024 * 1024))\(decimalSeparator)\(remainder) MB"
} else { } else {
return "\(size / (1024 * 1024)) MB" return "\(size / (1024 * 1024)) MB"
} }
} else if size >= 1024 { } else if size >= 1024 {
let remainder = (size % (1024)) / (102) let remainder = (size % (1024)) / (102)
if remainder != 0 || forceDecimal { if remainder != 0 || forceDecimal {
return "\(size / 1024),\(remainder) KB" return "\(size / 1024)\(decimalSeparator)\(remainder) KB"
} else { } else {
return "\(size / 1024) KB" return "\(size / 1024) KB"
} }