Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing Digits from a Number

Does anybody know if there is a way of removing (trimming) the last two digits or first two digits from a number. I have the number 4131 and I want to separate that into 41 and 31, but after searching the Internet, I've only managed to find how to remove characters from a string, not a number. I tried converting my number to a string, then removing characters, and then converting it back to a number, but I keep receiving errors.

I believe I will be able to receive the first two digit by dividing the number by 100 and then rounding the number down, but I don't have an idea of how to get the last two digits?

Does anybody know the function to use to achieve what I'm trying to do, or can anybody point me in the right direction.

like image 607
Jarron Avatar asked May 27 '15 06:05

Jarron


People also ask

How do you remove digits from a number?

To delete nth digit from starting:Count the number of digits. Loop number of digits time by counting it with a variable i. If the i is equal to (number of digits – n), then skip, else add the ith digit as [ new_number = (new_number * 10) + ith_digit ].


2 Answers

Try this:

var num = 1234

var first = num/100
var last = num%100

The playground's output is what you need.

Playground

like image 126
saurabh Avatar answered Sep 24 '22 23:09

saurabh


You can use below methods to find the last two digits

func getLatTwoDigits(number : Int) -> Int {
     return number%100; //4131%100 = 31
}
func getFirstTwoDigits(number : Int) -> Int {
    return number/100; //4131/100 = 41
}

To find the first two digit you might need to change the logic on the basis of face value of number. Below method is generalise method to find each digit of a number.

func printDigits(number : Int) {
    var num = number

    while num > 0 {
        var digit = num % 10 //get the last digit
        println("\(digit)")
        num = num / 10 //remove the last digit
    }
}
like image 24
kmithi Avatar answered Sep 22 '22 23:09

kmithi