I have an integer value, for example -12345678
, and I want to remove
the leading digit, so that the result is -2345678
.
One could convert it to string and remove 1 character, then remove 1 symbol.
Is there any simple way to achieve that?
I have an integer value, for example -12345678
, and I want to remove
the leading digit, so that the result is -2345678
.
One could convert it to string and remove 1 character, then remove 1 symbol.
Is there any simple way to achieve that?
A possible solution, using simple integer arithmetic:
func removeLeadingDigit(_ n: Int) -> Int {
var m = n.magnitude
var e = 1
while m >= 10 {
m /= 10
e *= 10
}
return n - n.signum() * Int(m) * e
}
At the end of the loop, m
is the leading digit of the given number
and e
is the corresponding power of 10
, e.g. for n = 432
we'll
get m = 4
and e = 100
. Some tests:
print(removeLeadingDigit(0)) // 0
print(removeLeadingDigit(1)) // 0
print(removeLeadingDigit(9)) // 0
print(removeLeadingDigit(10)) // 0
print(removeLeadingDigit(18)) // 8
print(removeLeadingDigit(12345)) // 2345
print(removeLeadingDigit(-12345)) // -2345
print(removeLeadingDigit(-1)) // 0
print(removeLeadingDigit(-12)) // -2
print(Int.max, removeLeadingDigit(Int.max)) // 9223372036854775807 223372036854775807
print(Int.min, removeLeadingDigit(Int.min)) // -9223372036854775808 -223372036854775808
Something like this:
let value = -12345678
var text = "\(value)"
if text.hasPrefix("-") {
let index = text.index(text.startIndex, offsetBy: 1)
text.remove(at: index)
} else if text.characters.count > 1 {
let index = text.index(text.startIndex, offsetBy: 0)
text.remove(at: index)
}
Output:
value = -12345678 will print out -2345678
value = 12345678 will print out 2345678
value = 0 will print out 0
Something like
let intValue = 12345678
let value = intValue % Int(NSDecimalNumber(decimal: pow(10, intValue.description.characters.count - 1)))
//value = 2345678
let n = -123456
let m = n % Int(pow(10, floor(log10(Double(abs(n))))))