Removing Digits from a Number

一笑奈何 提交于 2019-12-01 03:24:26

问题


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.


回答1:


Try this:

var num = 1234

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

The playground's output is what you need.




回答2:


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
    }
}


来源:https://stackoverflow.com/questions/30474347/removing-digits-from-a-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!