I was stunned to learn there is no? immediate way to get the mantissa/exponent of a CGFloat in Swift.
(Note that I want the two values, NOT a string representation in scientific notation format.)
These hopelessly undocumented properties Double.exponent, Double.significand are on Double but that’s quite different from wanting the “usual, human” mantissa/exponent. (Unless I’m drastically missing something.)
I typed out a function to do it, but doing so is crap for at least three major reasons that come to mind.
Is there a solution to this conundrum?
(*) Surprised there are not 100 questions about this issue on here!
extension CGFloat { // (ignored negatives for clarity)
var decomp: (CGFloat, CGFloat) {
var exponent: CGFloat = 0.0
var mantissa: CGFloat = self
while mantissa < 1.0 {
mantissa = mantissa * 10.0
exponent -= 1
}
while mantissa >= 10.0 {
mantissa = mantissa / 10.0
exponent += 1
}
print("check ... ", self, "(mantissa)E(exponent)")
return (mantissa, exponent)
}
}
hence ..
var x: CGFloat = 0.00123
print( "yo" , x.decomp)
x = 12
print( "yo" , x.decomp)
x = 1000
print( "yo" , x.decomp)
check ... 0.00123 1.23E-3.0 yo (1.23, -3.0) check ... 12.0 1.2E1.0 yo (1.2, 1.0) check ... 1000.0 1.0E3.0 yo (1.0, 3.0)
(†) Minor – I return the exp as a float since that seemed more consistent for the typical ways you’d then use such a thing, but IDK.