Search code examples
iosswiftbyteformatter

ByteCountFormatter number formate


I'm using ByteCountFormatter for converting Byte to Appropriate String,

func sizeFormate(size: Int) -> String {
    let bcf = ByteCountFormatter()
    bcf.allowedUnits = [.useMB,.useGB]
    bcf.countStyle = .binary
    return bcf.string(fromByteCount: Int64(size))
}

for example:

sizeFormate(size: 763917940) // output: 728.5 MB

// what I need is 728 MB // digit should not have fraction part 

How can we achieve this formate?


Solution

  • ByteCountFormatter have one property named: isAdaptive and by Default it is true. To hide fraction part just make this false

    Updated code:

    func sizeFormate(size: Int) -> String {
        let bcf = ByteCountFormatter()
        bcf.allowedUnits = [.useMB,.useGB]
        bcf.countStyle = .binary
        bcf.isAdaptive = false // change
        return bcf.string(fromByteCount: Int64(size))
    }
    

    Note: keep that in mind that it round of from 0.5 to 1

    it still shows fraction digits.. any other way?