3

I am using this image extension to calculate the image size in MB. And I am getting the size of my image with a comma(,) instead of a dot(.) like "1,7 MB"

extension UIImage {        
    func getFileSizeInfo(allowedUnits: ByteCountFormatter.Units = .useMB,
                         countStyle: ByteCountFormatter.CountStyle = .file) -> String? {
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = allowedUnits
        formatter.countStyle = countStyle
        return getSizeInfo(formatter: formatter)
    }

    func getSizeInfo(formatter: ByteCountFormatter, compressionQuality: CGFloat = 1.0) -> String? {
        guard let imageData = jpegData(compressionQuality: compressionQuality) else { return nil }
        return formatter.string(fromByteCount: Int64(imageData.count))
    }
}

Method calling:

var imageSizeInMB = image.getFileSizeInfo()
print(imageSizeInMB) //Output "1,7 MB" 

I need output like "1.7 MB"

I am not looking for "replace characters in a string".

Please help me here.

Mohit Kumar
  • 2,898
  • 3
  • 21
  • 34
  • 1
    Does this answer your question? [Any way to replace characters on Swift String?](https://stackoverflow.com/questions/24200888/any-way-to-replace-characters-on-swift-string) – NicolasElPapu Apr 28 '20 at 18:46
  • Unfortunately, `ByteCountFormatter` is the only formatter that doesn't allow to change locale. If locale that depends on system language is not good enough for you, you will have to duplicate the functionality yourself. Luckily, you can just use the normal `NumberFormatter` and divide the value in bytes by `1_024 * 1_024`. – Sulthan Apr 28 '20 at 18:52
  • I read a little bit in the ByteCountFormatter class and I found a property "isAdaptive". The default value of this is false and turned it to true. After that, I am getting the desired result. @Sulthan can you tell if this is right? – Mohit Kumar Apr 28 '20 at 19:01
  • That shouldn't really make a difference. This should be controlled only by the system language. – Sulthan Apr 28 '20 at 19:03
  • You can give it a try, After making it true I am getting dot(.) as expected. I double-checked this. – Mohit Kumar Apr 28 '20 at 19:25

1 Answers1

0

ByteCountFormatter doesn't have locale property to configure the target locale for output unlike NumberFormatter and DateFormatter ones so that it gets info fro the system's settings.

You can change the current locale to a locale with a needed decimalSeparator on your device or change the locale programatically on your app level:

extension NSLocale {
    @objc static var currentLocale = NSLocale(localeIdentifier: "en_US") // decimalSeparator = "."
    //@objc static var currentLocale = NSLocale(localeIdentifier: "fr_FR") // decimalSeparator = ","
}

let formatter = ByteCountFormatter()
formatter.allowedUnits = .useMB
let text = formatter.string(fromByteCount: 1_700_000)
print(text)

Outputs:

1.7 MB
iUrii
  • 11,742
  • 1
  • 33
  • 48