Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get nth digits of Integer in Swift? [duplicate]

Let's say I have a value representing the year 1927. Now I want to get the last 2 digits of said year. Is there an efficient way of doing this in Swift? I figured out the following method based on my SO research thus far:

// My goal is to start with 1927 and end with 27

let fullYear = 1927 as Float  // --> 1927 
let valueToSubtract = Int(fullYear/100)  // --> 19
let splitNumber = fullYear/100 as NSNumber  // --> 19.27
let decimalValue = Float(splitNumber) - Float(valueToSubtract)  // -->0.2700005
let finalNumber = Double(round(1000 * decimalValue)/10)  // --> 27

This seems overly cumbersome. I'm fairly new to programming and Swift, am I missing a simpler way?

like image 842
Aaron Avatar asked Jul 03 '15 05:07

Aaron


1 Answers

Last two digits - use division modulo operator: 1927 % 100 gives 27.

like image 184
Amadan Avatar answered Oct 21 '22 04:10

Amadan