I'm trying to remove all digits before the . period in a Double using NumberFormatter but for some reason, it only removes it if the digits are zeros.
Is it normal that when stating formatter.minimumIntegerDigits = 0 it doesn't remove all digits before the . unless they're zeros?
func formatDoubleAsStringFraction(number: Double)->String{
var formatter = NumberFormatter()
formatter.locale = NSLocale.current
formatter.minimumFractionDigits = 2 // two digits after the decimal point
formatter.minimumIntegerDigits = 0 // this will remove digits before Idecimal point
formatter.numberStyle = .decimal
let formatedNumber = formatter.string(for: number)
return formatedNumber!
}
formatDoubleAsStringFraction(number: 0.99) // outputs: .99
formatDoubleAsStringFraction(number: 000.99) // outputs: .99
formatDoubleAsStringFraction(number: 1.99) // outputs: 1.99 - why it doesn't remove the 1?
formatDoubleAsStringFraction(number: 123.99) // outputs: 123.99 - why it doesn't remove the 123?
Try setting
maximumIntegerDigits = 0That should force your output to have no integer digits. It worked in a quick test I did.
Edit:
This code:
Yields test output like this:
Which seems to match your desired output.
(Note that if you want exactly 2 fractional decimal digits, you probably want to set both
minimumFractionDigitsandmaximumFractionDigits.)